项目优化过程需要使用到的插件

8次阅读

共计 6860 个字符,预计需要花费 18 分钟才能阅读完成。

xtravel-pc-v1

erp PC 前端项目

依赖安装

npm install element-ui --save

借助 babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的

npm install babel-plugin-component -dev
npm install vuex --save

预编译语言

npm install sass --save
npm install css-loader --save
npm install sass-loader node-sass --save

表达验证依赖

npm install async-validator --save

ajax 依赖

npm install axios --save

token 解析插件

npm install jsonwebtoken --save

解决 ie 对 Promise(es6 语法)兼容问题,/ 在 main.js 文件夹中引入 /

npm install es6-promise --save

如果 chromedriver 安装出现问题,可以考虑使用如下命名

npm install --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver

storage 工具插件

npm install vue2-storage --save

加密解密依赖

npm install crypto-js --save

时间操作工具

npm install moment --save

图表

npm install echarts --save

金额工具

npm install numeral --save

vue-loader

  • vue-loader 在项目创建时会自动安装这个依赖,但是要注意版本要在“14.2.4”以上(包括“14.2.4”)

webpack-merge

解决线上打包图片的问题

npm install webpack-merge --save

vue-infinite-scroll

无限滚动组件

npm install vue-infinite-scroll --save

webpack-bundle-analyzer

项目优化报告插件

npm install webpack-bundle-analyzer --save-dev

生成报告

image-webpack-loader

图片压缩

npm install image-webpack-loader --save

compression-webpack-plugin

代码压缩

npm install compression-webpack-plugin --save-dev

webpack-uglify-harmony-plugin

js 代码压缩

npm install webpack-uglify-harmony-plugin --save

mini-css-extract-plugin

css 代码分离

npm install mini-css-extract-plugin --save

html-webpack-plugin

html 代码压缩

npm install html-webpack-plugin --save

optimize-css-assets-webpack-plugin

css 压缩

npm install optimize-css-assets-webpack-plugin --save-dev

babel-plugin-component

局部组件加载

npm i babel-plugin-component --save

prerender-spa-plugin

预渲染

npm i -D prerender-spa-plugin

babel-plugin-transform-remove-console

去除 console.log

npm i --D babel-plugin-transform-remove-console

出掉多余的 css

npm i -D glob-all purgecss-webpack-plugin

Build Setup

bash
# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run build

# build for production and view the bundle analyzer report
npm run build --report

# run unit tests
npm run unit

# run e2e tests
npm run e2e

# run all tests
npm test

示例 demo 查看说明

  1. 组件说明和描述
<!-- erp 项目中的组件和说明描述都放在 portal 项目下的 component-description.md 文件中 -->
portal->component-description.md 
  1. 组件 demo 地址:
<!-- 
  erp 项目中所有已封装的组件的 demo 都放在 frame 项目下的 demo 文件夹中
  demoComponent.vue 文件表示组件的 demo 实例,可以查看是否有自己需要的组件
  demoForm.vue 表示 form 表单组件
  invoiceAdd.vue form 表单组件,代码生成器生成的
  invoiceList.vue table 列表组件,代码生成器生成的
-->
frame -> demo -> demoComponent.vue
              -> demoForm.vue
              -> invoiceAdd.vue
              -> invoiceList.vue 
  1. 全局公用样式查看
<!-- 
  erp 系统中的全局公共演示放在 portal 项目下的 src -> css 文件 -> public -> commonBase.scss 
  commonBase.scss  全局公共样式,无须引入,直接拿过来用
  commonBase.css 是 commonBase.html 中,使用的静态资源文件

  具体样式如何,可以直接在浏览器中打开 commonBase.html
-->

vue.config.js

const webpack = require('webpack')
const merge = require('webpack-merge') // base64
const APP_NAME = require('./package.json').name // 项目名称
const InsertScriptPlugin = require('./scripts/InsertScriptWebpackPlugin') // 插入脚本插件
const PROXY = require('./config/proxy') // 子项目 url 代理配置文件
const modules = require('./config/modules') // 要加载的子项目配置文件
const path = require('path')
// 优化插件
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const glob = require("glob-all");
const PurgecssPlugin = require("purgecss-webpack-plugin");

function resolve (dir) {return path.join(__dirname, dir)
}

module.exports = {
  publicPath: './',
  
  productionSourceMap: false, // 是否开启 cssSourceMap, TODO??? [xsw] 打包应该设置未 false???

  /**
   * Type: Object
   * 所有 webpack-dev-server 的选项都支持
   * 有些值像 host、port 和 https 可能会被命令行参数覆写
   * 有些像 publicPath 和 historyApiFallback 不应该被修改,因为它们需要和开发服务器的 baseUrl 同步以保障正常工作
   */
  devServer: {
    port: 18080, // 项目端口
    proxy: PROXY, // 这会告诉服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到 PROXY 中配置的 url
    disableHostCheck: true, // 关闭 host 检测(配置了这个才可以通过域名访问)
    compress: true, // 代码压缩
  },

  /**
   *  配置 Webpack 其他选项
   *  警告
      有些 webpack 选项是基于 vue.config.js 中的值设置的,所以不能直接修改。例如你应该修改 vue.config.js 中的 outputDir 选项而不是修改 output.path;你应该修改 vue.config.js 中的 baseUrl 选项而不是修改 output.publicPath。这样做是因为 vue.config.js 中的值会被用在配置里的多个地方,以确保所有的部分都能正常工作在一起。*/

  configureWebpack: {
    // 这里必须引入 vue
    externals: {vue: 'Vue',},
    // 分离 插件
    optimization: {
      minimizer: true,
      splitChunks: {
        chunks: 'async',
        minSize: 3000,
        maxSize: 0,
        minChunks: 1,
        maxAsyncRequests: 5,
        maxInitialRequests: 10,
        automaticNameDelimiter: '~',
        name: true,
        cacheGroups: {
          libs: {
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial"
          },
          elementUI: {
            name: "chunk-elementUI",
            priority: 20,
            test: /[\\/]node_modules[\\/]element-ui[\\/]/,
            chunks: "all"
          },
          echarts: {
            name: "chunk-echarts",
            priority: 30,
            test: /[\\/]node_modules[\\/]echarts[\\/]/,
            chunks: "all"
          },
          ckeditor: {
            name: "chunk-ckeditor",
            priority: 40,
            test: /[\\/]node_modules[\\/]@ckeditor[\\/]ckeditor5-build-classic[\\/]build[\\/]/,
            chunks: "all"
          },
          styles: {
            name: 'styles',
            test: /\.(sa|sc|c)ss$/,
            chunks: 'initial',
            enforce: true,
          },
          moment: {
            name: "chunk-moment",
            priority: 50,
            test: /[\\/]node_modules[\\/]moment[\\/]/,
            chunks: "all"
          },
          zrender: {
            name: "chunk-zrender",
            priority: 60,
            test: /[\\/]node_modules[\\/]zrender[\\/]/,
            chunks: "all"
          },
          main: {
            name: "chunk-main",
            priority: 70,
            test: /[\\/]src[\\/]main[\.]js/,
            chunks: "all"
          }
        }
      }
    },
    plugins: [
      new webpack.DefinePlugin({'XM.MN': JSON.stringify(APP_NAME),
      }),
      new InsertScriptPlugin({files: modules}),
      // 启动 report 
      new BundleAnalyzerPlugin({
        generateStatsFile: true,
        statsOptions: {source: false}
      }),
      // 去除 moment 中 i18n
      new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /zh-cn/),
      // 声明‘production’生产环境最小体积
      new webpack.DefinePlugin({
        'process.env': {NODE_ENV: JSON.stringify('production')
        }
      }),
      // 在代码层面上进行压缩
      new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
        threshold: 0, // 只有大小大于该值的资源会被处理
        minRatio:0.8, // 只有压缩率小于这个值的资源才会被处理
        deleteOriginalAssets: false // 删除原文件
      }),
      // 去除 多余 css
      new PurgecssPlugin({paths: glob.sync([resolve("./**/*.vue")]),
        extractors: [
          {
            extractor: class Extractor {static extract(content) {
                const validSection = content.replace(/<style([\s\S]*?)<\/style>+/gim,
                  ""
                );
                return validSection.match(/[A-Za-z0-9-_/:]*[A-Za-z0-9-_/]+/g) || []}
            },
            extensions: ["html", "vue"]
          }
        ],
        whitelist: ["html", "body"],
        whitelistPatterns: [/el-.*/, /-(leave|enter|appear)(|-(to|from|active))$/, /^(?!cursor-move).+-move$/, /^router-link(|-exact)-active$/],
        whitelistPatternsChildren: [/^token/, /^pre/, /^code/]
      })
    ],
  },
  chainWebpack: config => {
    // 路径别名
    config.resolve.alias
      .set('@', resolve('src'))
      .set('@css', resolve('src/assets/css'))
      .set('@fonts', resolve('src/assets/fonts'))
      .set('@img', resolve('src/assets/image'))
      .set('@api', resolve('src/api'))
      .set('@bApi', resolve('src/baseApi'))
      .set('@bCps', resolve('src/baseComponents'))
      .set('@cps', resolve('src/components'))
      .set('@api', resolve('src/api'))
      .set('@page', resolve('src/pages'))

    //base64 相关代码
    // 图片压缩优化 image-webpack-loader
    config.module
      .rule('images')
      .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
      .use('image-webpack-loader')
      .loader('image-webpack-loader')
      .options({mozjpeg: { progressive: true, quality: 65},
        optipng: {enabled: false},
        pngquant: {quality: "65-90", speed: 4},
        gifsicle: {interlaced: false},
        webp: {quality: 75}
      })
      .end()},

  // 要全局使用的 scss 变量、Mixin 在这里引入(注:这类 scss 文件需要每个项目都放一份, 这个配置也需要每个项目都写一份)css: {
    loaderOptions: {
      sass: {
        data: `
        @import "@css/globalCite/defaultUrlVariable.scss";
        @import "@css/globalCite/urlVariable.scss";
        @import "@css/globalCite/variable.scss";
        @import "@css/globalCite/themeVariable.scss";
        @import "@css/globalCite/themeMixin.scss";
        `
      }
    }
  }
}

正文完
 0