webpack
如果 require 中含有表达式,由于编译时不清楚具体导入了哪个模块,所以会创建一个上下文,会对该目录下所模块的引用,可以使用匹配正则表达式的请求来导入这些模块,上下文模块中存在一个映射,该映射用于将请求转换为 模块 ID,这意味着webpack能够动态导入
可以通过 require.context() 函数实现自定义上下文,传入三个参数,要搜索的目录,是否还继续搜索子目录,匹配文件的正则表达式
require.context(
directory,
(useSubdirectories = true),
(regExp = /^\.\/.*$/),
(mode = 'sync')
);
Tree shaking 通常描述 移除 js 上下文中的死代码(即永远不会执行的代码)
通过 package.json 的 "sideEffects" 属性即可实现此目的。
{
"name": "your-project",
"sideEffects": false
}
sideEffects 和 useExports (更多的被称为 tree shaking) 是俩种不同的优化方式,sideEffects 更为有效是因为他允许跳过整个模块/文件和整个文件子树,useExports 依赖于 terser 检测语句中的副作用,是 一个js任务
过 /*#__PURE__*/ 注释可以告诉 webpack 某个函数调用无副作用。它可以被放到函数调用之前,用来标记此函数调用是无副作用的
环境
开发环境中,我们通常需要强大的 source map 和 live reloading 或者 hmr ,而生产环境则需要,压缩 bundle 更轻量的 source map,资源优化,但是也会出现 生产环境和开发环境,重复配置,为了不重复配置,我们会有一个 webpack-merge 工具来 合并配置
安装
npm install --save-dev webpack-merge
webpack.common.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Production',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
};
webpack.dev.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
static: './dist',
},
});
webpack.prod.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
});
nodejs 通过设置 package.json 中的属性来显示设置文件模块类型,在package.json中设置 type:"module" 会强制 package.json 下的文件使用 es ,而 设置成 CommonJs 会强制使用 CommonJs 模块