js兼容性处理

  1. 下载
  2. npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/polyfill core-js
const { resolve } = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCssAssetsWebpackPlugin = require("optimize-css-assets-webpack-plugin");
//设置node环境变量,默认是生产环境production
process.env.NODE_ENV = "development";
module.exports = {
  entry: "./src/js/index.js",
  output: {
    filename: "js/bundle.js",
    path: resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          //将css转化为js
          "css-loader",
          //使用postcss-loader,解决css的兼容性问题
          {
            loader: "postcss-loader",
            options: {
              postcssOptions: {
                ident: "postcss",
                plugins: () => [
                  //帮助css找到package.json中的browserslist里面的配置,通过加载指定的css样式
                  require("postcss-preset-env")(),
                ],
              },
            },
          },
        ],
      },
      {
        // 在 package.json 中 eslintConfig --> airbnb
        test: /\.js$/,
        exclude: /node_modules/,
        // 优先执行
        enforce: "pre",
        loader: "eslint-loader",
        options: { fix: true },
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          presets: [
            [
              "@babel/preset-env",
              {
                useBuiltIns: "usage",
                corejs: { version: 3 },
                targets: { chrome: "60", firefox: "50" ,ie:'9'},
              },
            ],
          ],
        },
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      minify: {
        // 移除空格
        collapseWhitespace: true,
        // 移除注释
        removeComments: true,
      },
    }),
    new MiniCssExtractPlugin({
      //对打包后css重命名,并将之放入一个文件
      filename: "css/built.css",
    }),
    new OptimizeCssAssetsWebpackPlugin(),
  ],
  mode: "production",
};

js压缩

把mode变成production就可以了

html压缩

const { resolve } = require('path'); 
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = { entry: './src/js/index.js',
                  output: { filename: 'js/built.js',
                           path: resolve(__dirname, 'build') },
                  plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', 
                              // 压缩 html 代码 
                      minify: { 
                        // 移除空格 
                        collapseWhitespace: true, 
                        // 移除注释
                        removeComments: true } }) ],
                  mode: 'production' };