Webpack build后,主文件有920k,有什么好方法可以做到小一些

#1

项目介绍
项目用了webpack + redux + react-router
构建出来的文件有900多K

印象中,上一个项目构建出来是400多K…

#2

这是我的webpack.product.config.js配置信息

var path = require('path');
var webpack = require('webpack');
var ImageminPlugin = require('imagemin-webpack-plugin').default

module.exports = {
    devtool: false,
    entry: {
        index: [
            './src/index.js'
        ]
    },
    output: {
        path: path.join(__dirname, '/dist'),
        filename: '[name].js'
    },
    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            output: {
                comments: false
            }
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        })
    ],
    resolve: {
        modulesDirectories: [
            'node_modules', 'common', 'img'
        ]
    },
    module: {
        noParse : [],
        loaders: [{
            test: /\.jsx?$/,
            loader: 'babel',
            exclude: /node_modules/,
            include: [
                path.join(__dirname,'src')
            ],
            query: {
                cacheDirectory: true,
                "presets": ["react", "es2015"]
            }
        },{
            test: /\.css$/,
            exclude: /(node_modules|styles)/,
            loaders: ['style', 'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]', 'autoprefixer?{browsers:["> 5%", "ie 9"]}']
        },{
            test: /\.css$/,
            include: [
                path.join(__dirname,'node_modules'),
                path.join(__dirname,'styles')
            ],
            loaders: ['style', 'css']
        },{
            test: /\.(png|jpg|jpeg|gif)$/i,
            loader: 'file'
        },{
            test: /\.(svg|eot|ttf|woff|woff2)$/i,
            loader: 'url-loader'
        },{
            test: /\.html$/i,
            loader: 'file?name=[name].[ext]'
        }]
    },
};
#3

我也是如此,你的有解决么?

#4

externals

#5

webpack dllplugin 最有效的方案

#6

https://chrisbateman.github.io/webpack-visualizer/

试试这个,看看是那个lib占的比较多

#7

如果你想在页面使用 <script/>引入第三方库,需要加入配置

  externals: {
    'react': 'React',
    'react-dom': 'ReactDOM',
    'redux': 'Redux',
    'react-router': 'ReactRouter',
  }

这样编译的时候,webpack 会忽略这些第三方库。


如果你是要把所有第三方库打包在一起,那引入方式也有些注意的地方,比如:
import { Router } from 'react-router'
打包的时候会把整个 react-router 打包进来,并不只是 Router 这个组件。

正确的按需引入方式应该是:import Router from 'react-router/lib/Router'

#8

最简单的方法是使用webpack -p命令,如果这样压缩打包还是不够小,就需要考虑使用其他额外的压缩工具了。

#9

我的方式是这样的:

export NODE_ENV=production && webpack -p --progress --profile --colors

作为参考。