如何提高webpack的执行速度?

时间:2017-09-24 17:52:45

标签: javascript webpack webpack-2

实际上,我为使用reactjs的网站编写了webpack。因为我有很多图像和scss文件,所以创建bundle.js文件需要花费更多的时间,直到网站处于加载状态。那么,我如何才能提高执行速度。

webpack.config.js

const path = require("path");
const webpack = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

let config = {
  entry: ["babel-polyfill", "./app/js/index.js"],
  output: {
    path: path.resolve(__dirname, "public"),
    filename: "./build.js",
    //publicPath: "/"
  },
  resolve: {
    alias: {
      "js": path.resolve(__dirname, "app/js"),
      "css": path.resolve(__dirname, "app/css")
    },
    extensions: [".js", ".jsx"]
  },
  module: {
    rules: [
      {test: /\.(js|jsx)$/, loader: "babel-loader"},
      {
       test: /\.(eot|svg|ttf|woff|woff2)$/,
       loader: 'url-loader'
     },
      {test: /\.scss$/, loader: ExtractTextPlugin.extract(["css-loader", "sass-loader"])},
      {test: /\.(jpg|gif|png)$/, loader: "file-loader", options: {name: "./images/[name].[ext]"}},
    ]
  },

  devServer: {
    historyApiFallback: true
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./app/index.html"
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        sassLoader: {
          includePaths: ["app/css"]
        }
      }
    }),
    new ExtractTextPlugin({
      filename: "style.css",
      allChunks: true
    })
  ]
};

if (process.env.NODE_ENV === "production") {
  config.plugins.push(
    new webpack.DefinePlugin({
      "process.env": {
        "NODE_ENV": JSON.stringify(process.env.NODE_ENV)
      }
    }),
    new webpack.optimize.UglifyJsPlugin()
  );
}

module.exports = config;

1 个答案:

答案 0 :(得分:1)

除了调整配置外,您还可以使用webpack --watch让webpack监视您的源文件,并在您更改内容时重新编译。第一次编译仍然是完整的,但之后每次只重新编译必要的部分,这可以将编译时间从30秒减少到1或2秒。

更好的方法是设置webpack的devserver进行热重新加载,这也会监视并逐步编译,但此外还会在浏览器中更新您的应用程序,因此您无需重新加载页面并失去反应州。设置起来可能有点挑剔,但值得一试。