nodejs开发:webpack4.39.0配置

webpack是nodejs开发中,经常需要用到工具;貌似不同的版本的配置稍有差异,经常碰到各种错误
这里本人基于目前最新版本进行了配置测试

安装相关package

创建目录
mkdir webpacktest && cd webpacktest

npm init -y
npm i -D webpack webpack-cli

npm i -D html-webpack-plugin html-loader

npm i -D webpack-dev-server

npm i -D @babel/core babel-loader @babel/preset-env

npm i -D file-loader

npm i -D node-sass style-loader css-loader sass-loader mini-css-extract-plugin

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
{
"name": "webpacktest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start:dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"babel-loader": "^8.0.6",
"css-loader": "^3.1.0",
"file-loader": "^4.1.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.12.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.39.0",
"webpack-cli": "^3.3.6",
"webpack-dev-server": "^3.7.2"
}
}

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
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use:{
loader: 'babel-loader'
}
},
{
test: /\.html$/,
use: [{
loader: 'html-loader',
options: {
minimize: true
}
}],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader'
}
]
},
{
test:/\.scss$/,
use:[
"style-loader",
"css-loader",
"sass-loader"
]
}
]
},
plugins: [new HtmlWebPackPlugin({
template: './src/index.html',
filename: './index.html'
}),
new MiniCssExtractPlugin({
filename:"[name].css",
chunkFilename:"[id].css"
})
]
}

输入命令 npm run build进行打包
npm run start:dev进行开发

安装静态服务器
npm i http-server -g
http-server -o(运行服务器)

坚持原创技术分享,您的支持是我前进的动力!