webpack5项目搭建Vue-Cli(生产环境)

Posted 天界程序员

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了webpack5项目搭建Vue-Cli(生产环境)相关的知识,希望对你有一定的参考价值。

我们这里的webpack.prod.js采用复用react-cli的开发模式的配置进行改造。

step1–添加vue-loader配置

1、rule.loader


  test: /\\.vue$/,
  loader: 'vue-loader',
,

2、插件配置

const  VueLoaderPlugin  = require('vue-loader')
const  DefinePlugin  = require('webpack')

 new VueLoaderPlugin(),
    // 解决页面警告
 new DefinePlugin(
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
 ),

step2–修改文件扩展名

  resolve: 
    extensions: ['.vue', '.js', '.json'], // 自动补全文件扩展名,让vue可以使用
  ,

step3–babel只处理js

// babel处理js资源

  test: /\\.js$/,
  loader: 'babel-loader',
  options: 
    cacheDirectory: true,
    cacheCompression: false,
  ,
,

step4–补充依赖包

npm i mini-css-extract-plugin css-minimizer-webpack-plugin copy-webpack-plugin -D

npm i image-minimizer-webpack-plugin imagemin -D

npm install imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo -D

step5–修改命令路径

"scripts": 
    "start": "npm run dev",
    "dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.dev.js",
    "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.prod.js"
  ,

此外,vue-loader不支持oneOf操作。

step6–现阶段详细配置

// webpack.prod.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const htmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const  VueLoaderPlugin  = require("vue-loader");
const  DefinePlugin  = require("webpack");

const getStyleLoaders = (preProcessor) => 
  return [
    MiniCssExtractPlugin.loader,
    "css-loader",
    
      loader: "postcss-loader",
      options: 
        postcssOptions: 
          plugins: [
            "postcss-preset-env", // 能解决大多数样式兼容性问题
          ],
        ,
      ,
    ,
    preProcessor,
  ].filter(Boolean);
;

module.exports = 
  entry: "./src/main.js",
  output: 
    path: path.resolve(__dirname, "../dist"),
    filename: "static/js/[name].[contenthash:10].js",
    chunkFilename: "static/js/[name].[contenthash:10].chunk.js",
    assetModuleFilename: "static/js/[hash:10][ext][query]",
    clean: true,
  ,
  module: 
    rules: [
      
        // 用来匹配 .css 结尾的文件
        test: /\\.css$/,
        // use 数组里面 Loader 执行顺序是从右到左
        use: getStyleLoaders(),
      ,
      
        test: /\\.less$/,
        use: getStyleLoaders("less-loader"),
      ,
      
        test: /\\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      ,
      
        test: /\\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      ,
      
        test: /\\.(png|jpe?g|gif|svg)$/,
        type: "asset",
        parser: 
          dataUrlCondition: 
            maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
          ,
        ,
      ,
      
        test: /\\.(ttf|woff2?)$/,
        type: "asset/resource",
      ,
      
        test: /\\.(jsx|js)$/,
        include: path.resolve(__dirname, "../src"),
        loader: "babel-loader",
        options: 
          cacheDirectory: true,
          cacheCompression: false
        ,
      ,
      // vue-loader不支持oneOf
      
        test: /\\.vue$/,
        loader: "vue-loader", // 内部会给vue文件注入HMR功能代码
        options: 
          // 开启缓存
          cacheDirectory: path.resolve(
            __dirname,
            "node_modules/.cache/vue-loader"
          ),
        ,
      ,
    ],
  ,
  plugins: [
    new ESLintWebpackPlugin(
      context: path.resolve(__dirname, "../src"),
      exclude: "node_modules",
      cache: true,
      cacheLocation: path.resolve(
        __dirname,
        "../node_modules/.cache/.eslintcache"
      ),
    ),
    new HtmlWebpackPlugin(
      template: path.resolve(__dirname, "../public/index.html"),
    ),
    new CopyPlugin(
      patterns: [
        
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          toType: "dir",
          noErrorOnMissing: true,
          globOptions: 
            ignore: ["**/index.html"],
          ,
          info: 
            minimized: true,
          ,
        ,
      ],
    ),
    new MiniCssExtractPlugin(
      filename: "static/css/[name].[contenthash:10].css",
      chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
    ),
    new VueLoaderPlugin(),
    new DefinePlugin(
      __VUE_OPTIONS_API__: "true",
      __VUE_PROD_DEVTOOLS__: "false",
    ),
  ],
  optimization: 
    // 压缩的操作
    minimizer: [
      new CssMinimizerPlugin(),
      new TerserWebpackPlugin(),
      new ImageMinimizerPlugin(
        minimizer: 
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: 
            plugins: [
              ["gifsicle",  interlaced: true ],
              ["jpegtran",  progressive: true ],
              ["optipng",  optimizationLevel: 5 ],
              [
                "svgo",
                
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    
                      name: "sortAttrs",
                      params: 
                        xmlnsOrder: "alphabetical",
                      ,
                    ,
                  ],
                ,
              ],
            ],
          ,
        ,
      ),
    ],
    splitChunks: 
      chunks: "all",
    ,
    runtimeChunk: 
      name: (entrypoint) => `runtime~$entrypoint.name`,
    ,
  ,
  resolve: 
    extensions: [".vue", ".js", ".json"],
  ,
  mode: "production",
  devtool: "source-map",
;

以上是关于webpack5项目搭建Vue-Cli(生产环境)的主要内容,如果未能解决你的问题,请参考以下文章

webpack5项目搭建Vue-Cli(开发模式)

webpack5项目搭建Vue-Cli(配置优化)

webpack5项目搭建React-Cli(生产模式)

webpack5项目搭建React-Cli(配置合并)

webpack5 查漏补缺

webpack5 查漏补缺