目录:

package.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@vue/compiler-sfc": "^3.3.4",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.8.1",
"dart-sass": "^1.25.0",
"friendly-errors-webpack-plugin": "^1.7.0",
"html-webpack-plugin": "^5.5.1",
"sass": "^1.62.1",
"sass-loader": "^13.3.1",
"scss-loader": "^0.0.1",
"style-loader": "^3.3.3",
"ts-loader": "^9.4.3",
"typescript": "^5.1.3",
"vue": "^3.3.4",
"vue-loader": "^17.0.1",
"webpack": "^5.85.0",
"webpack-cli": "^5.1.3",
"webpack-dev-server": "^4.15.0"
}
}

webpack.config.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// webpack.config.js基于node环境,所以需要用common js模块化
const { Configuration } = require("webpack")
const path = require("path")
const htmlWebpackPlugin = require("html-webpack-plugin")
const { VueLoaderPlugin } = require("vue-loader/dist/index")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin")

/**
* @type {Configuration}
*/
const config = {
// 运行模式
// 开发环境中打包的代码不会被压缩
mode: "development",
// 入口文件
entry: "./src/main.ts",
module: {
rules: [
{
test: /\.vue$/,
use: "vue-loader"
},
// 使用多个loader时要注意先后顺序
{
test: /\.scss$/,
use: ["style-loader","css-loader","sass-loader"]
},
{
test: /\.css$/,
use: ["style-loader","css-loader"]
},
{
test: /\.ts$/,
loader: "ts-loader",
// ts-loader要针对vue单文件组件进行特殊处理
options: {
configFile: path.resolve(process.cwd(),"tsconfig.json"),
appendTsSuffixTo:[/\.vue$/]
}
}
]
},
// 出口
output: {
// 文件名
filename: "[hash].js",
// 输出位置
path: path.resolve(__dirname, "dist"),
// 每次打包钱清空输出文件夹
clean: true
},
// 文件处理
resolve: {
// 目录别名
alias: {
"@": path.resolve(__dirname,"src")
},
// 自动识别后缀
extensions: [".vue",".ts",".js"]
},
// 终端输出内容级别
stats: "errors-only",
// 服务设置
devServer: {
proxy: {},
port: 11451,
hot: true,
open: true
},
// 插件
plugins: [
new htmlWebpackPlugin({
// 应用页面
template: "./public/index.html"
}),
// 支持vue
new VueLoaderPlugin(),
// 每次打包时清空输出文件夹
new CleanWebpackPlugin(),
// 美化webpack终端输出
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: ["Your application is running!"]
}
})
],
// 性能优化
externals: {
// CDN引入vue,这样vue就不会被打进包里了
// 减小体积,但是要求更好的网速
vue: "Vue"
}
}

module.exports = config