设置环境变量
DefinePlugin插件
webpack提供defineplugin插件,允许重写符合的自由变量free variables。
自由变量即没有var申明的全局变量,例如:
if(bar === 'bar') {console.log('bar');}
如果bar是全局变量且为”bar”, 那么该语句等效于
console.log('bar');,这是defineplugin插件的核心
设置process.env.NODE_ENV
如果我们有类似if(process.env.NODE_ENV === 'development')语句,那么可以直接用development替换process.env.NODE_ENV
// libs/parts.js...exports.setFreeVariable = function(key, value) {const env = {};env[key] = JSON.stringify(value);return {plugins: [new webpack.DefinePlugin(env)]};}
// webpack.config.js...// Detect how npm is run and branch based on thatswitch(process.env.npm_lifecycle_event) {case 'build':config = merge(common,{devtool: 'source-map'},parts.setFreeVariable('process.env.NODE_ENV','production'),parts.minify(),parts.setupCSS(PATHS.style));break;default:...}module.exports = validate(config);
最终
app.js压缩结果是25.4k,另外如果浏览器支持,还可以用gzip进一步压缩
babel-plugin-transform-inline-environment-variables插件可以实现同样的效果还有
react-dom没有加入,当然可以选择更小的preact或者react-lite他们提供更少的功能,但是却更小
