1.entry
webpack 查找依赖的入口文件配置,入口文件既可以一个也可以是多个。
单页面应用入口配置
通常做法配置:
index.js 单页面应用入口文件,vendor.js 第三方依赖库,polyfill.js 特性填充库,
// 导出配置
module.exports = {
entry: {
vendor: './src/vendor.js',
polyfill: './src/polyfill.js',
index: './src/index.js',
},
}
多页面应用入口配置
和单页面应用类似,但不同页面会不同有入口文件,这种情况高效的做法就不是直接写死在 entry 里面了,而是通过生成 webpack.config 时,扫描指定目录确定每个页面的入口文件以及所有的页面。
例如:你的页面都放置在 src/pages 目录下面,并且你的每个页面单独一个目录,并且其中有 index.html 和 index.js
配置如下:
const path = require('path');
const fs = require('fs');
// 处理公共entry
const commonEntry = ['./src/vendor.js', './src/polyfill.js'];
// 页面目录
const PAGES_DIR = './src/pages/'; const entry = {};
// 遍历页面目录
const getPages = () => { return fs.readdirSync(PAGES_DIR).filter(item => {
let filepath = path.join(PAGES_DIR, item, 'index.js');
if (!fs.existsSync(filepath)) {
filepath = `${filepath}x`; // js
}
if (!fs.existsSync(filepath)) {
return false;
}
return true;
});
};
getPages(options).forEach(file => {
const name = path.basename(file);
// 加入页面需要的公共入口
entry[name] = [...commonEntry, `${PAGES_DIR}/${file}/index`];
});
// 导出配置 module.exports = { entry, };
那么,入口 boundle 如何插入对应的 html 中
const plugins = [];
if (mode === 'single') {
// 单页面只需要一次HtmlWebpackPlugin
plugins.push(
new HtmlWebpackPlugin({
minify: false,
filename: 'index.html',
template: './src/index.html',
})
);
}
if (mode === 'multi') {
// 多页面遍历目录,使用目录下面的html文件
// 不同页面的配置不同,每个页面都单独配置一个html
// 所有页面的公共部分可以抽离后,通过模版引擎编译处理
// 具体的方式后面部分loader中提到
const files = getPages(options);
files.forEach(file => {
const name = path.basename(file);
file = `${PAGES_DIR}/${file}/index.html`;
// 添加runtime脚本,和页面入口脚本
const chunks = [`runtime~${name}`, name];
plugins.push(
new HtmlWebpackPlugin({
minify: false,
filename: `${name}.html`,
template: file,
chunks,
})
);
});
}
// 导出配置
module.exports = {
plugins,
};
2.output
{
output:{
// name是你配置的entry中key名称,或者优化后chunk的名称
// hash是表示bundle文件名添加文件内容hash值,以便于实现浏览器持久化缓存支持
filename: '[name].[hash].js',
// 在script标签上添加crossOrigin,以便于支持跨域脚本的错误堆栈捕获
crossOriginLoading:'anonymous',
//静态资源路径,指的是输出到html中的资源路径前缀
publicPath:'https://7.ur.cn/fudao/pc/',
path: './dist/',//文件输出路径
}
}
3.resolve
resolve: {
modules: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname,'node_modules'),
],
alias: {
components: path.resolve(__dirname, '/src/components'),
},
}
扩展 如果你使用了绝对路径后,可能就发现vscode智能代码导航就失效了,别慌!请在想目录下面配置jsconfig.json
文件解决这个问题,配置和上面对应:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"src/*": ["./src/*"],
"components/*": ["./src/components/*"],
"assets/*": ["./src/assets/*"],
"pages/*": ["./src/pages/*"]
}
},
"include": ["./src/**/*"]
}
4.module
module: {
// 这些库都是不依赖其它库的库 不需要解析他们可以加快编译速度
// 通常可以将那些大型的库且已经编译好的库排除,减少webpack对其解析耗时
noParse: /node_modules\/(moment|chart\.js)/,
rules: [
{
test: /\.jsx?$/,
use: resolve('babel-loader'),
// 需要被这个loader处理的资源
include: [
path.resolve(projectDir, 'src'),
path.resolve(projectDir, 'node_modules/@tn'),
].filter(Boolean),
// 忽略哪些压缩的文件
exclude: [/(.|_)min\.js$/],
}
]