hooyantsing's Blog

P18 生产环境基本配置

字数统计: 477阅读时长: 2 min
2020/11/30

尚硅谷2020最新版Webpack5实战教程

项目结构

– project/

|– build/

|– src/

​ |– css/

​ |– imgs/

​ |– js/

​ |– index.js (webpack启动入口)

​ |– media/

​ |– index.html

编写配置文件

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const { resolve } = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 定义nodejs环境变量 决定使用 browserslist 哪个环境
process.env.NODE_ENV = 'production';

// 复用 loader
const commonCssLoader = [
// package.json -> browserslist
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader'
];

module.exports = {
entry: './src/js/index.js',
output: {
filename: 'js/built.js',
path: resolve(__dirname, 'build'),
publicPath:'./'
},
module: {
rules: [
{
test: /\.css$/,
use: [...commonCssLoader]
},
{
test: /\.less$/,
use: [...commonCssLoader, 'less-loader']
},
{
// package.json -> eslintConfig
test: /\.js$/,
exclude: /node_modules/,
// 优先执行
enforce: 'pre',
loader: 'eslint-loader',
options: {
fix: true
}
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
useBuiltIns: 'entry',
corejs: {
version: 3
},
targets: {
chrome: '60',
firefox: "60",
ie: '9',
safari: '10',
edge: '17'
}
}
]
],
"plugins": ["@babel/plugin-transform-runtime"]
}
},
{
test: /\.(jpg|png|gif)/,
loader: 'url-loader',
options: {
limit: 8 * 1024,
name: '[hash:10].[ext]',
outputPath: 'imgs',
esModule: false
}
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
exclude: /\.(js|css|less|html|jpg|png|gif)/,
loader: 'file-loader',
options: {
outputPath: 'media'
}
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/built.css'
}),
new OptimizeCssAssetsWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
minify: {
collapseWhitespace: true,
removeComments: true
}
})
],
mode: 'production',
devServer: {
contentBase: resolve(__dirname,'build'),
compress: true,
port: 3000
}
};

postcss.config.js

1
2
3
4
5
module.exports = {
plugins: [
require('postcss-preset-env')
]
}

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"browserslist": {
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"production": [
">0.2%",
"not dead",
"not op_mini all"
]
},
"eslintConfig": {
"extends": "airbnb-base"
}

注意,已知存在的问题。

css内引用的图片,错误路径 css/imgs/xxx.jpg ,导致图片无法正常显示。

CATALOG
  1. 1. 项目结构
  2. 2. 编写配置文件