使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(七)添加静态文件
笔特 | 11/16/2022, 6:46:36 AM | 398 次阅读
1 引言
为了能够更好的理解webpack,特准备了这份从零开始开始搭建教程,不使用官方的脚手架,不使用预定义配置,完全从零开始搭建一个使用 Webpack5 构建的 Vue3 + TypeScript 的项目开发环境。一个网站系统中如果将图片或者第三方js等不会改变的文件放入代码中会增加webpack打包的时间,所以需要添加静态文件目录,将静态文件放入该目录中直接引入。
关键词
- Webpack5
- Vue3
- TypeScript
- JavaScript
文章列表
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(一)搭建编译环境
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(二)配置HTML模板
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(三)添加Vue环境
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(四)添加Vue的样式
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(五)添加Less支持
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(六)添加Vue的TS支持
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(七)添加静态文件
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(八)不同环境的配置
- 使用 Webpack 从零开始搭建 Vue3 + TS 开发环境(九)ES语法转换
2 静态JS文件
提示
静态资源文件分为两类:
第一类是public文件夹中,可以直接在html中引用的
第二类是src/assets中,会被webpack打包处理的文件
(1) 新建静态目录public
(2) 新建文件public/staticjs.js
console.log("staticjs")
1
(3) 修改index.html,在head中加入如下代码
<script src="/staticjs.js" type="text/javascript"></script>
1
预览结果
4 添加图片
在public/images和src/assets中分别放入两个图片(大小不同)
5 安装依赖并配置
yarn add -D file-loader
// webpack.config.cjs
// 添加rules配置
{
test: /\.(png|jpeg|jpg|gif|bmp)$/,
use: [{
loader: 'file-loader',
options: {
limit: 20000,
name: "img/[name].[hash:8].[ext]"
}
}]
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
// webpack.config.cjs
// 设置打包路径别名
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
}
},
1
2
3
4
5
6
7
2
3
4
5
6
7
// tsconfig.json
// 配置语法检查路径别名和types路径
//
{
"compilerOptions": {
"typeRoots": [
"node_modules/@types", // 默认值
"types"
],
"paths": {
"@/*":[
"./src/*"
]
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
6 改写代码
<template>
<div class="app-main">
<a class="a-button" @click="onTestClick">测试 Vue 文件:{{count}}</a>
<br/>
<img src="@/assets/logo.png" alt="logo" style="width:50px;height:50px;"/>
<img src="@/assets/example.png" alt="" style="width:50px;height:50px;"/>
<br/>
<img src="/image/logo.png" alt="logo" style="width:50px;height:50px;"/>
<img src="/image/example.png" alt="" style="width:50px;height:50px;"/>
</div>
</template>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
// types/image.d.ts
// ts语法检查会报错,必须声明图片文件
declare module "*.png"
declare module "*.jpg"
declare module "*.gif"
declare module "*.bmp"
declare module "*.jpeg"
1
2
3
4
5
6
7
2
3
4
5
6
7
你可以将前面的vue声明文件移到types文件夹下
7 编译打包
yarn build
注意
没有public文件夹的内容
8 使用Webpack的拷贝文件插件
yarn add copy-webpack-plugin
// 注意老版本的插件用法有差异,我这里用的版本是11.0.0
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
plugins: [
new CopyWebpackPlugin({
patterns: [{
from: __dirname + '/public',
to: __dirname + '/dist'
}],
}),
],
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
重新yarn build