为什么我的webpack bundle.js和vendor.bundle.js文件这么大?

18

我所有的React项目文件大小都非常大(bundle.js为4.87 MB,vendor.bundle.js为2.87 MB)。我不知道为什么会这么大。我已经启用了uglifyJS,但它似乎并没有帮助很多(5.09> 4.87 MB和2.9> 2.87 MB)。

var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

require('es6-promise').polyfill();

var config = {
  entry: {
    app: [
      './src/entry.jsx'
    ],
    vendor: [
      'react',
      'lodash',
      'superagent'
    ]
  },
  output: {
    path: './build',
    filename: "bundle.js"
  },
  eslint: {
    configFile: './.eslintrc'
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      { test: /\.(js|jsx)$/, loaders: ['react-hot', 'babel?experimental'], exclude: /node_modules/},
      { test: /\.(js|jsx)$/, loader: "eslint-loader", exclude: /node_modules/},
      { test: /\.json$/, loader: 'json' },
      { test: /\.yml$/, loader: 'json!yaml' },
      { test: /\.scss$/, loader: 'style!css!sass' },
      { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({'process.env': {'NODE_ENV': JSON.stringify('production')}}),
    new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.bundle.js"),
    new webpack.optimize.UglifyJsPlugin({minimize: true}),
    new webpack.NoErrorsPlugin()
  ]
};

module.exports = config;

我的package.json

{
  "license": "MIT",
  "engines": {
    "iojs": ">= 1.6.2"
  },
  "scripts": {
    "create:index": "mustang -t index.tmpl -i config.json -o build/index.html",
    "predev": "mkdir -p build/ && npm run create:index",
    "dev": "webpack-dev-server --host 0.0.0.0 --hot --progress --colors --content-base build",
    "backend": "NODE_ENV=production node server/server.js",
    "backend:dev": "DEBUG=tinderlicht node server/server.js",
    "predeploy": "mkdir -p build/ && npm run create:index",
    "deploy": "NODE_ENV=production webpack -p",
    "test": "node webpack-mocha.config.js"
  },
  "devDependencies": {
    "autoprefixer-loader": "^3.2.0",
    "axios": "^0.7.0",
    "babel": "^5.8.23",
    "babel-core": "^5.8.25",
    "babel-eslint": "^4.1.3",
    "babel-loader": "^5.3.2",
    "bluebird": "^2.10.2",
    "css-loader": "^0.19.0",
    "es6-collections": "^0.5.1",
    "es6-promise": "^3.0.2",
    "eslint": "^1.6.0",
    "eslint-loader": "^1.1.0",
    "eslint-plugin-react": "^3.5.1",
    "extract-text-webpack-plugin": "^0.8.2",
    "file-loader": "^0.8.1",
    "firebase": "^2.3.1",
    "fireproof": "^3.0.3",
    "jquery": "^2.2.0",
    "json-loader": "^0.5.1",
    "jsonld": "^0.4.2",
    "jsx-loader": "^0.13.2",
    "lodash": "^3.3.0",
    "mustang": "^0.1.3",
    "node-sass": "^3.3.3",
    "react": "^0.14.0",
    "react-dom": "^0.14.0",
    "react-hot-loader": "^1.1.5",
    "sass-loader": "3.0.0",
    "style-loader": "^0.12.4",
    "superagent": "^1.4.0",
    "url-loader": "^0.5.5",
    "webpack": "^1.5.3",
    "webpack-dev-server": "^1.7.0"
  },
  "dependencies": {
    "body-parser": "^1.15.0",
    "cors": "^2.7.1",
    "debug": "^2.2.0",
    "express": "^4.13.4",
    "mustache": "^2.2.1",
    "nodemailer": "^2.1.0",
    "nodemailer-sendmail-transport": "^1.0.0",
    "react-radio-group": "^2.2.0",
    "uglifyjs": "^2.4.10"
  }
}

有没有人知道如何解决这个问题?


2
David Guan的建议听起来不错。您正在使用devtool:"eval-source-map",该选项提供良好的开发人员体验,但它会将整个源代码作为数据URL包含在内。您不应在生产环境中使用此选项。 - Johannes Ewald
6个回答

15

我强烈建议使用Webpack Bundle Analyzer来缩小你的包大小 (https://github.com/th0r/webpack-bundle-analyzer)。你可以看到是什么使你的包变得如此庞大。你可能还在使用firebase、lodash和jquery。除了使用webpack生产插件外,尝试使用ignore来忽略你不需要的东西,并像这样只导入你需要的内容: 在webpack插件中:

    new webpack.IgnorePlugin(/^\.\/auth$/, /firebase$/),
    new webpack.IgnorePlugin(/^\.\/storage$/, /firebase$/),
    new webpack.IgnorePlugin(/^\.\/messaging$/, /firebase$/),

在你的导入中:

 const Firebase: any = require('firebase/app');  require('firebase/database');

对于lodash来说,只引入你需要的部分或者创建一个自定义的构建(https://lodash.com/custom-builds):

import find from 'lodash/find' 

你也可以创建自定义的jQuery构建。


5

编辑

我不确定您是使用Mac / iOS还是Windows,但我注意到两件事:

1:"deploy": "NODE_ENV=production webpack -p"看起来不正确,您必须在构建过程中设置变量以进行开发和部署,在这里您没有进行设置。

2:您必须先在终端/命令提示符上设置它。

下面是一个用于webpack压缩和部署的示例,您需要进行一些调整,但希望这可以帮助您。

您首先必须在命令提示符上设置此node环境变量,在Windows中打开它或在Mac中的终端中输入:

Mac: export NODE_ENV=production

Windows: set NODE_ENV=production

你可以在Windows中使用echo或在Mac中使用list来检查变量是否已添加。
然后,在你的webpack.config.js文件中:
    var PROD = process.env.NODE_ENV == 'production';
    var config = {
      entry: {
            app: [
          './src/entry.jsx'
        ],
        vendor: [
          'react',
          'lodash',
          'superagent'
        ],
         output: {
           path: './build',
           filename: PROD ? "bundle.min.js" : "bundle.js"
         },
         plugins: PROD ? [
              new webpack.optimize.UglifyJsPlugin({minimize: true}),
              new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min.js'),
          ]:[
            new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
          ]
};

在您的 package.json 文件中,您可以设置以下脚本:
如果您使用的是 Windows 操作系统:
"scripts": {
         "dev": "set NODE_ENV=development&&webpack-dev-server --host 0.0.0.0 --hot --progress --colors --content-base build",
        "deploy": "set NODE_ENV=production&&webpack -p"
    }

如果您使用的是 Mac IOS: 如果导出不起作用,请改用 set,与 Windows 不同的是 && 后面需要加空格。

"scripts": {
         "dev": "export NODE_ENV=development&& webpack-dev-server --host 0.0.0.0 --hot --progress --colors --content-base build",
        "deploy": "export NODE_ENV=production&& webpack -p"
    }

使用命令“npm run watch”进行开发环境的构建,使用命令“npm run deploy”将其构建为生产环境下的缩小版本。

5
NODE_ENV=production webpack -p 确实设置了环境变量。 - SamuelN

4
我已经设置了一个仓库,只包含React / React Dom和一个Hello Word React组件。vendor.js文件大小为189 KB。 https://github.com/timarney/react-setup
var path = require('path')
var webpack = require('webpack')

var config = {
  entry: {
    app: path.resolve(__dirname, './src/main.js'),
    vendors: ['react']
  },
  output: {
    path: './src',
    filename: 'bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './src',
    port: 3000
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel'
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      output: {
        comments: false
      },
      compress: {
        warnings: false,
        screw_ie8: true
      }
    }),
    new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js')
  ]
}

if (process.env.NODE_ENV === 'production') {
  config.output.path = path.join(__dirname, 'dist/')
}

module.exports = config

注意:我通过一个NPM脚本设置了NODE ENV。
"scripts": {
    "start": "webpack-dev-server",
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "NODE_ENV=production webpack -p && cp src/index.html dist/index.html"
  },

1
如果有人使用OccurenceOrderPlugin,请确保名称已更新为OccurrenceOrderPlugin。 - Kushal Jain

3

2

在生产环境中,React 要求你将NODE_ENV设为'production',并通过Uglify来运行它——这可以消除许多额外的冗余、控制台日志等。确保在webpack构建时设置该环境变量(例如,在命令行中输入NODE_ENV=production webpack)。


1
使用sudo npm install -g source-map-explorer命令安装source-map-explorer,然后使用source-map-explorer path/to/files/*.js命令运行它。该程序会分析您的捆绑包并在浏览器中打开一个HTML页面,详细说明每个依赖项对总大小的贡献以及您自己的代码对总大小的贡献。如下图所示:Screenshot of source-map-explorer at work

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接