Webpack打包vue项目(优化--无注释),开发环境,生产环境

  1.webpack.config.js配置

注意:使用到path.resolve(__dirname,"...")绝对路径的,看自己的路径是否正确

const path = require("path");
const EslintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const { VueLoaderPlugin } = require("vue-loader");
const { DefinePlugin } = require("webpack");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
const isProduction = process.env.NODE_ENV === "production";


const getStyleLoaders = (pre) => {
  return [
    isProduction ? MiniCssExtractPlugin.loader : "vue-style-loader",
    "css-loader",
    {
      // 处理css兼容性问题
      // 配合package.json中browserslist来指定兼容性
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env"],// 能解决大多数样式兼容性问题
        },
      },
    },
    pre && {
      loader: pre,
      options:
        pre === "sass-loader"
          ? {
            additionalData: `@use "@/styles/element/index.scss" as *;`,
          }
          : {},
    },
  ].filter(Boolean);
};

module.exports = {
  entry: "./src/main.js",
  output: {
    path: isProduction ? path.resolve(__dirname, "../dist") : undefined,
    filename: isProduction ? "static/js/[name].[contenthash:10].js" : "static/js/[name].js",// 入口文件打包输出资源命名方式
    chunkFilename: isProduction ? "static/js/[name].[contenthash:10].chunk.js" : "static/js/[name].chunk.js",// 动态导入输出资源命名方式,要想实现动态导入,需要使用路由懒加载
    assetModuleFilename: "static/media/[hash:10][ext][query]",// 图片、字体等资源命名方式(注意用hash)
    // 清除上一次dist目录下的文件
    clean: true,
  },
  module: {
    rules: [
      // 处理css
      {
        test: /\.css$/,
        use: getStyleLoaders(),
      },
      {
        test: /\.less$/,
        use: getStyleLoaders("less-loader"),
      },
      {
        test: /\.s[ac]ss$/,
        use: getStyleLoaders("sass-loader"),
      },
      {
        test: /\.styl$/,
        use: getStyleLoaders("stylus-loader"),
      },
      // 处理图片
      {
        test: /\.(jpe?g|png|gif|webp|svg)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024,// 小于10kb的图片会被base64处理
          },
          //   修改输出资源和路径
        //  generator: {
            // 将图片文件输出到 static/imgs 目录中
            // 将图片文件命名 [hash:8][ext][query]
            // [hash:8]: hash值取8位
            // [ext]: 使用之前的文件扩展名
            // [query]: 添加之前的query参数
          //  filename: "static/images/[hash:8][ext][query]",
          //},
        },
      },
      // 处理其他资源
      {
        test: /\.(woff2?|ttf)$/,
        type: "asset/resource",
      },
      // 处理js
      {
        test: /\.js$/,
        include: path.resolve(__dirname, "../src"), 
        loader: "babel-loader",
        options: {
          cacheDirectory: true,// 开启babel编译缓存,记录上一次缓存,可以加快打包速度
          cacheCompression: false,//不压缩缓存文件,因为压缩缓存文件占用时间
        },
      },
      {
        test: /\.vue$/,
        loader: "vue-loader",
        options: {
          // 开启缓存
          cacheDirectory: path.resolve(__dirname, "../node_modules/.cache/vue-loader"),
        },
      },
    ],
  },
  // 处理html
  plugins: [
    new EslintWebpackPlugin({
      // 指定j检查文件根目录
      context: path.resolve(__dirname, "../src"),
      exclude: "node_modules",
      // 提升打包速度:开启缓存
      cache: true,
      // 缓存所放位置
      cacheLocation: path.resolve(__dirname, "../node_modules/.cache/.eslintcache"),
    }),

    new HtmlWebpackPlugin({
      // 以 public/index.html 为模板创建文件
      // 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
      template: path.resolve(__dirname, "../public/index.html"),
    }),
    isProduction &&
    new MiniCssExtractPlugin({
      filename: "static/css/[name].[contenthash:10].css",
      chunkFilename: "static/css/[name].[contenthash:10].chunk.css",
    }),
    isProduction &&
    new CopyPlugin({

      patterns: [
        {
          // 将public下面的资源复制到dist目录去(除了index.html)
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          globOptions: {
            // 忽略index.html文件
            ignore: ["**/index.html"],
          },
        },
      ],
    }),
    new VueLoaderPlugin(),
    // cross-env定义的环境变量给打包工具使用
    // DefinePlugin定义环境变量给源代码使用,从而解决vue3页面警告的问题
    new DefinePlugin({
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
    }),
    // 按需加载element-plus
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [
        ElementPlusResolver({
          // 自定义主题,引入sass
          importStyle: "sass",
        }),
      ],
    }),
  ].filter(Boolean),
  mode: isProduction ? "production" : "development",
  devtool: isProduction ? "source-map" : "cheap-module-source-map",
  optimization: {
    // 代码分割配置
    splitChunks: {
      chunks: "all",// 对所有模块都进行分割
      cacheGroups: {
        // 没写的配置的用默认配置即可
        vue: {
          test: /[\\/]node_modules[\\/]vue(.*)?[\\/]/,
          name: "vue-chunk",
          priority: 40,
        },
        // 如果项目中使用element-plus,此时将所有node_modules打包在一起,那么打包输出文件会比较大。
        // 所以我们将node_modules中比较大的模块单独打包,从而并行加载速度更好
        // 如果项目中没有,请删除
        elementPlus: {
          test: /[\\/]node_modules[\\/]element-plus[\\/]/,
          name: "elementPlus-chunk",
          priority: 30,
        },
        libs: {
          test: /[\\/]node_modules[\\/]/,
          name: "libs-chunk",
          priority: 20, // 权重最低,优先考虑前面内容
        },
      },
    },
    // 提取runtime文件
    runtimeChunk: {
      name: (entrypoint) => `runtime~${entrypoint.name}.js`, // runtime文件命名规则
    },
    // 压缩的操作
    minimize: isProduction,
    minimizer: [
      new CssMinimizerWebpackPlugin(),
      new CssMinimizerPlugin(),
      new TerserWebpackPlugin(),
      new ImageMinimizerPlugin({
        // 对图像最小化的处理
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,//告诉 ImageMinimizerPlugin 使用 imageminGenerate 方法来执行图像最小化处理。
          options: {
            plugins: [

              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
  // webpack解析模块加载选项
  resolve: {
    // 自动补全文件扩展名
    extensions: [".vue", ".js", ".json"],
    // 路径别名
    alias: {
      "@": path.resolve(__dirname, "../src"),
    },
  },
  devServer: {
    host: "localhost",
    port: 3000,
    open: true,
    hot: true, // 热更新,开启HMR,
    historyApiFallback: true, // 解决前端路由刷新404问题
  },
  performance: false,//关闭performance 并不会优化生成的文件大小,它只是关闭了相关的警告和提示信息。
};

2.package.json

{
  "name": "vue-cli",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run dev",
     //cross-env是一个跨平台设置环境变量的工具,它允许你在不同的操作系统上通过命令行方式设置环境变量。使用cross-env可以确保在不同的平台上都能正确地设置环境变量。
    // 这是设置环境变量 NODE_ENV 的部分。NODE_ENV 是一个常见的环境变量,用于指示当前环境的模式
    // --config选项用于告诉Webpack使用指定的配置文件来进行构建。
    "dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js"
  },
   .....
  "browserslist": [
    // 这三个取的是交集
    "last 2 version", //市面上所有浏览器的最新两个版本
    "> 1%",  // 覆盖99%的浏览器
    "not dead"  // 死了的就不要了
  ],
  "devDependencies": {
    "@babel/core": "^7.17.10",
    "@babel/eslint-parser": "^7.17.0",
    "@vue/cli-plugin-babel": "^5.0.4",
    "babel-loader": "^8.2.5",
    "copy-webpack-plugin": "^10.2.4",
    "cross-env": "^7.0.3",
    "css-loader": "^6.7.1",
    "css-minimizer-webpack-plugin": "^3.4.1",
    "eslint-plugin-vue": "^8.7.1",
    "eslint-webpack-plugin": "^3.1.1",
    "html-webpack-plugin": "^5.5.0",
    "image-minimizer-webpack-plugin": "^3.2.3",
    "imagemin": "^8.0.1",
    "imagemin-gifsicle": "^7.0.0",
    "imagemin-jpegtran": "^7.0.0",
    "imagemin-optipng": "^8.0.0",
    "imagemin-svgo": "^10.0.1",
    "less-loader": "^10.2.0",
    "mini-css-extract-plugin": "^2.6.0",
    "postcss-loader": "^6.2.1",
    "postcss-preset-env": "^7.5.0",
    "sass": "^1.51.0",
    "sass-loader": "^12.6.0",
    "stylus-loader": "^6.2.0",
    "unplugin-auto-import": "^0.7.1",
    "unplugin-vue-components": "^0.19.3",
    "vue-style-loader": "^4.1.3",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^5.72.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.9.0"
  },
  .....
}

3.  .eslintrc.js

module.exports = {
  // root: true 表示当前配置文件是根配置文件,不会继续向上查找其他配置文件,并将该文件作为项目的独立配置。
  root: true,
  env: {
    node: true, // 启用node中全局变量
    //browser: true, // 启用浏览器中全局变量
  },
  // 继承规则
  extends: ["plugin:vue/vue3-essential", "eslint:recommended"],
  // 解析选项
  parserOptions: {
    // 运用的是规则,需要安装
    parser: "@babel/eslint-parser",
  },
  
};

4.babel.config.js

module.exports = {
  // 这也是一个规则,需要下载@vue/cli-plugin-babel
  presets: ["@vue/cli-plugin-babel/preset"]
};

5. main.js(入口文件)

console.log(123,'@@@@');
import count from "./public/js/count";
import sum from "./public/js/sum";
import './public/css/index.css'
import './public/css/index1.css'
console.log(count(2, 1));
console.log(sum(1, 2, 3, 4));
....

// 判断是否支持HMR功能
// 原生没有插件的时候使用此方法,但这样写会很麻烦,所以实际开发我们会使用其他 loader 来解决。比如:vue-loader, react-hot-loader。就不用再写此段代码了
if (module.hot) {
  // 引入js文件
  module.hot.accept("./js/count.js", function (count) {
    const result1 = count(2, 1);
    console.log(result1);
  });

  module.hot.accept("./js/sum.js", function (sum) {
    const result2 = sum(1, 2, 3, 4);
    console.log(result2);
  });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
为了优化webpack打包vue项目,你可以考虑以下几个方面: 1. 使用代码分割:将代码拆分成多个小块,按需加载,减小初始加载的文件大小。可以使用webpack的SplitChunksPlugin插件来进行代码分割。 2. 使用懒加载:对于一些不常用或者较大的模块,可以使用懒加载的方式来延迟加载,减小初始加载的文件大小。可以通过vue-router的异步路由或者webpack的import函数来实现。 3. 压缩代码:使用webpack的UglifyJsPlugin插件来压缩代码,减小文件体积。 4. 使用缓存:通过设置webpack的output.filename和output.chunkFilename选项来生成带有hash的文件名,以便浏览器能够缓存文件,减少重复请求。 5. 图片优化:将图片进行压缩和转换为base64编码,以减小文件大小。可以使用url-loader或者file-loader插件来处理图片。 6. 清除无用代码:使用webpack的Tree Shaking特性去除未使用的代码,减少输出文件体积。 7. 配置合理的Devtool选项:在开发环境中使用sourcemap来方便调试代码,而在生产环境中使用cheap-source-map或者none等选项来减小构建时间和文件大小。 8. 优化打包时的性能:使用happypack插件来多线程处理webpack的loader和babel-loader,使用ParallelUglifyPlugin插件来并行压缩代码,提高构建速度。 以上是一些常见的webpack打包vue项目优化方法,你可以根据具体情况选择适合你项目优化策略。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值