WebSalon

六畳一间的堂吉诃德

0%

webpack学习记录-2

devServer配置

  DevServer: 用来自动化编译、打开浏览器,刷新浏览器,只会在内存中编译打包,不会有文件输出。

开发环境简单配置

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
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { resolve } = require('path');

module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/index.js',
path: resolve(__dirname, 'prod'),
},
mode: 'production',
module: {
rules: [
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader'],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|gif|jpg)$/,
loader: 'url-loader',
options: {
outputPath: 'img',
limit: 8 * 1024,
name: '[hash:10].[ext]',
esModule: false,
},
},
{
test: /\.html$/,
loader: 'html-loader',
options: {
esModule: false,
},
},
{
exclude: /\.(less|css|jpg|png|gif|html|js)$/,
loader: 'file-loader',
options: {
outputPath: 'media',
name: '[hash:10].[ext]',
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
devServer: {
contentBase: resolve(__dirname, 'build'), // 项目构建后的路径
port: 3000, // 服务端口
compress: true, // 启用gzip压缩
open: true, // 自动打开浏览器
},
};

CSS相关处理

提取CSS成单独文件

   使用插件:MiniCssExtractPlugin
示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'less-loader',
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[chunkhash:10].css', // 对输出的css文件进行重命名
}),
],
}

注意: 提取css成单独文件,就不能再用style-loader

-------- 本文结束 感谢阅读 --------
  • 本文标题: webpack学习记录-2
  • 本文作者: SevenNorth
  • 创建时间: 2021年10月15日 - 15时10分
  • 修改时间: 2023年01月30日 - 06时01分
  • 本文链接: http://blog.lovinghlx.cn/FE/webpack/webpack-learn-2/
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!