Web前端之路让前端飞Web 前端开发

Webpack 指南(中)

2017-10-20  本文已影响75人  青栀灬

一. Tree Shaking

npm install uglifyjs-webpack-plugin --save-dev
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

modules.exports = {
  //...
  plugins: [new UglifyJSPlugin],
};

二. 生产环境构建

npm install webpack-merge --save-dev
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    app: './src/index.js',
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({ title: 'Hello Webpack!' }),
  ],
  output: {
    filename: '[name].[hash:4].js',
    path: path.resolve(__dirname, 'dist'),
  },
};
const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
  },
});
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  devtool: 'source-map',
  plugins: [new UglifyJSPlugin()],
});
"scripts": {
  "start": "webpack-dev-server --open --config webpack.dev.js",
  "build": "webpack --config webpack.prod.js"
},
// webpack.prod.js
plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify('production'),
    },
  }),
],
if (process.env.NODE_ENV === 'production') {
  // production
} else {
  // development
}

三. 代码分离

1. 多入口

plugins: [
  new webpack.optimaize.CommonsChunkPlugin({
    name: 'common',
  }),
],

2. 动态导入

output: {
  filename: '[name].bundle.js',
  chunkFilename: '[name].bundle.js',
  path: path.resolve(__dirname, 'dist'),
},

四. 缓存

1. 输出文件名称

2. 提取模板

plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: 'runtime',
  }),
],

3. 提取 vendor

module.exports = {
  entry: {
    main: './src/index.js',
    vendor: ['lodash'],
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'runtime',
    }),
  ],
};

4. 模块标识符

plugins: [
  new webpack.HashedModuleIdsPlugin(),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'runtime',
  }),
],
上一篇下一篇

猜你喜欢

热点阅读