resolve
1 2 3 4 5 6 7 8 9 10 11
| resolve: { extensions: [], alias: { comonents: './src/components/' }, modules: ['./src/components','node_modules'] }
|
modules
有时项目当中会有一些模块被大量 被其他模块依赖和导入,由于其他模块的位置分布不定,针对不同的文件都要去计算被导入文件的相对路径,
这个路径有时候会很长,如:import Button from '../../../components/button'
,
这时可以通过 webpack 进行优化,假如那些被大量导入的模块都在 ./src/components/
目录下,通过 webpack 配置
1 2 3 4
| resolve: { modules: ['./src/components','node_modules'] }
|
之后,可以简单的通过 import 'button'
导入
mainFields
此选项就是在 package.json
文件不存在或者 package.json
文件中的 main
字段没有返回一个有效路径,则按照顺序查找 resolve.mainFields
配置选项中指定的文件名,看是否能在 import/require
目录下匹配到一个存在的文件名。
有一些第三方模块会针对不同环境提供几分代码。 例如分别提供采用 ES5 和 ES6 的2份代码,这2份代码的位置写在 package.json 文件里,如下:
1 2 3 4
| { "jsnext:main": "es/index.js", "main": "lib/index.js" }
|
Webpack 会根据 mainFields 的配置去决定优先采用那份代码, mainFields 默认如下:
1
| mainFields: ['browser', 'main']
|
Webpack 会按照数组里的顺序去 package.json 文件里寻找,只会使用找到的第一个。
假如你想优先采用 ES6 的那份代码,可以这样配置:
1
| mainFields: ['jsnext:main', 'browser', 'main']
|
plugins
clean-webpack-plugin
清理指定文件(夹)
html-webpack-plugin
指定编译模板 .html 文件,此后基于这个文件来编译
devServer
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| devServer: {
contentBase: './dist', static: { directory: path.join(__dirname, 'public'), }, compress: false, host: 'localhost', port: 5000 }
|
1 2 3 4 5 6 7 8 9 10
| devServer: { stats: 'errors-only' }
module.exports = { stats: 'errors-only' }
|
1 2 3 4 5 6 7 8
| contentBase: './dist',
static: { directory: path.join(__dirname, 'dist'), },
static: './dist'
|
问题 1. 热更新失效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| module.exports = { target: 'web', }
"browserslist": { "development": [ "last 1 chrome version", "last 1 firfox version", "last 1 safary version" ], "production": [ ">0.2%", "not dead", "not op_mini all" ] }
|
自动编译,HMR 启动,页面依旧不更新