vue2项目搭建和打包优化方案

363 阅读1分钟

一、初始化脚手架项目:

vue create vue-demo

二、切换到vue-demo项目所在文件夹,安装依赖:

cnpm install

三、安装dependencies:

cnpm install vue-router vuex axios moment echarts ant-design-vue --save

(这里我UI框架用的是:ant-design-vue)

四、安装devDependencie:

cnpm install less less-loader --save-dev

为了能全局使用某些样式文件,可以安装style-resources-loader 和 vue-cli-plugin-style-resources-loader:

cnpm install style-resources-loader vue-cli-plugin-style-resources-loader --save-dev

代码优化,设置gzip压缩,安装 compression-webpack-plugin:

cnpm install compression-webpack-plugin --save-dev

五、打包优化

// vue.config.js
"use strict";
const path = require("path")
const webpack = require('webpack')
const CompressionWebpackPlugin = require("compression-webpack-plugin")

const resolve = dir => path.resolve(__dirname, dir)
const isProduction = process.env.NODE_ENV !== "development"

const cdn = {
  // 忽略打包的第三方库
  externals: {
    vue: "Vue",
    vuex: "Vuex",
    "vue-router": "VueRouter",
    axios: "axios"
  },
  // 通过cdn引入
  js: [
    'https://cdn.bootcss.com/vue/2.6.11/vue.runtime.min.js',
    'https://cdn.bootcss.com/vue-router/3.1.2/vue-router.min.js',
    'https://cdn.bootcss.com/vuex/3.1.2/vuex.min.js',
    'https://cdn.bootcss.com/axios/0.19.2/axios.min.js',
    'https://cdn.bootcss.com/moment.js/2.24.0/moment.min.js',
    'https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js',
  ],
  css: []
}

module.exports = {
  publicPath: "/",
  outputDir: "dist",
  assetsDir: "static",
  indexPath: "index.html",
  productionSourceMap: false,
  chainWebpack: config => {
    // 添加别名
    config.resolve.alias
      .set("@", resolve("src"))
      .set("@imgs", resolve("src/assets/imgs"))
      .set("@views", resolve("src/views"));

    config.plugin("copy")
      .tap(args => {
        args[0][0].to = "resource";
        return args
      });
	// 移除prefetch插件
    config.plugins.delete('prefetch-index');
	// // 移除 preload 插件,避免加载多余的资源
    config.plugins.delete('preload-index');
	// moment优化,避免加载多余的moment资源
    config.plugin('ignore').use(new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn$/));
	
    config.optimization.minimize(true)
      
	// 配置cdn引入
    config.plugin('html').tap((args) => {
      args[0].cdn = cdn;
      return args;
    });

  }, 
  configureWebpack: config => {
    // 忽略打包配置
    config.externals = cdn.externals;
    if(isProduction) {
      // gzip压缩
      const productionGzipExtensions = ["html", "js", "css"]
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: "[path].gz[query]",
          algorithm: "gzip",
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8,
          deleteOriginalAssets: false
        })
      );
      // 公共代码抽离
      config.optimization = {
        splitChunks: {
          cacheGroups: {
            // 公用模块抽离
            common: {
              chunks: "initial",
              minSize: 0,
              minChunks: 2
            },
            // 第三方库
            vendor: {
              priority: 1,
              test: /node_modules/,
              chunks: "initial",
              minSize: 0,
              minChunks: 2
            }
          }
        }
      }

    }
  },
  // 保存全局less
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [resolve('./src/assets/css/variables.less')]
    }
  },

  devServer: {
    open: true,
    port: 8086,
    hotOnly: true,
    // proxy: {
    //   '/api': {
    //     target: process.env.VUE_APP_API,
    //     changeOrigin: true, 
    //     secure: false,
    //     pathRewrite: {
    //       '^/api': '', 
    //     },
    //   },
    // },
  }
}

git地址:gitee.com/wxxkk/vue2-…

参考了打包优化文章:www.cnblogs.com/jiekzou/p/1…