Webpack

env.d.ts

1
2
3
4
5
6
7
//配置vue 声明文件不然ts 识别不了vue 后缀

declare module "*.vue" {
import { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}

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
{
"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.2.45",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.7.2",
"friendly-errors-webpack-plugin": "^1.7.0",
"html-webpack-plugin": "^5.5.0",
"less": "^4.1.3",
"less-loader": "^11.1.0",
"style-loader": "^3.3.1",
"ts-loader": "^9.4.1",
"typescript": "^4.9.3",
"vue": "^3.2.45",
"vue-loader": "^17.0.1",
"webpack": "^5.75.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
}
}

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
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', //入口文件
output: {
filename: '[hash].js',
path: path.resolve(__dirname, 'dist'), //出口文件
clean: true //在生成文件之前清空 output 目录 webpack5
},
module: {
rules: [
{
test: /\.vue$/, //哪些文件会被转换
use: 'vue-loader' //在转换时使用的loader
},
{
test: /\.css$/, //解析css
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', "less-loader"]
},
{
test: /\.ts$/, //解析ts
loader: "ts-loader",
options: {
configFile: path.resolve(process.cwd(), 'tsconfig.json'),
appendTsSuffixTo: [/\.vue$/]
},
}
]
},
resolve: {
alias: {
"@": path.resolve(__dirname, 'src') //别名
},
extensions: ['.vue', '.ts', '.js']
},
devServer: {
port: 9001,
},
stats: "errors-only",
plugins: [
new htmlWebpackPlugin({
template: './public/index.html'
}),
new VueLoaderPlugin(),
// new CleanWebpackPlugin() //打包前清空dist目录 webpack5以下
// ...
new FriendlyErrorsWebpackPlugin({
// 成功的时候输出
compilationSuccessInfo: {
messages: [`Your application is running here: http://localhost:8080`]
},
// 是否每次都清空控制台
clearConsole: true,
})
],
externals: {
vue: "Vue" //CDN引入,减小打包面积
}
}

module.exports = config