高级优化5. Cache缓存

每次打包时 js 文件都要经过 Eslint 检查 和 Babel 编译,速度比较慢。如果可以缓存之前的 Eslint 检查 和 Babel 编译结果,这样第二次打包时速度就会更快了。

使用 Cache 对 Eslint 检查 和 Babel 编译结果进行缓存,只会对新修改的内容进行检查。

使用:

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/main.js",
  output: {
    path: undefined, // 开发模式没有输出,不需要指定输出目录
    filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
    // clean: true, // 开发模式没有输出,不需要清空输出结果
  },
  module: {
    rules: [
      {
        oneOf: [
          {
            test: /\.css$/,
            use: ["style-loader", "css-loader"],
          }
          {
            test: /\.js$/,
            include: path.resolve(__dirname, "../src"), // 也可以用包含
            loader: "babel-loader",
            // babel 开启缓存 cache 
            options: {
              cacheDirectory: true, // 开启babel编译缓存
              cacheCompression: false, // 缓存文件不要压缩,压缩太耗时
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new ESLintWebpackPlugin({
      context: path.resolve(__dirname, "../src"),
      exclude: "node_modules", 
      // ESLint 开启缓存
      cache: true, 
      // 缓存目录
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "../public/index.html"),
    }),
  ],
  // 开发服务器
  devServer: {
    host: "localhost", 
    port: "3000", 
    open: true, 
    hot: true, 
  },
  mode: "development",
  devtool: "cheap-module-source-map",
};

你可能感兴趣的:(webpack,前端)