Plug-ins to be used in the project optimization process

xtravel-pc-v1

erp PC front-end project

Dependent installation

npm install element-ui --save

With the help of babel-plugin-component, we can only introduce the required components in order to reduce the size of the project.

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

Precompiled language

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

Expressing Verification Dependence

npm install async-validator --save

ajax dependence

npm install axios --save

token parsing plug-in

npm install jsonwebtoken --save

Solve the problem of ie compatibility with Promise (es6 grammar), / Introduce in main.js folder/

npm install es6-promise --save

If there is a problem with the chrome driver installation, consider using the following naming

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

storage Tool Plug-in

npm install vue2-storage --save

Encryption and decryption dependence

npm install crypto-js --save

Time Operating Tool

npm install moment --save

Chart

npm install echarts --save

Money tool

npm install numeral --save

vue-loader

  • vue-loader automatically installs this dependency when a project is created, but note that the version should be above "14.2.4" (including "14.2.4").

webpack-merge

Solve the problem of packaging pictures online

npm install webpack-merge --save

vue-infinite-scroll

Infinite scroll component

npm install vue-infinite-scroll --save

webpack-bundle-analyzer

Project optimization report plug-in

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

Generate report

image-webpack-loader

Picture compression

npm install image-webpack-loader --save

compression-webpack-plugin

Code compression

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

webpack-uglify-harmony-plugin

js code compression

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

mini-css-extract-plugin

css code separation

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

html-webpack-plugin

html code compression

npm install html-webpack-plugin --save

optimize-css-assets-webpack-plugin

css compression

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

babel-plugin-component

Local component loading

npm i babel-plugin-component --save

prerender-spa-plugin

pre-render

npm i -D prerender-spa-plugin

babel-plugin-transform-remove-console

Remove console.log

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

Get rid of the redundant 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

Examples demo view instructions

  1. Component description and description
<!-- erp Components and descriptions in the project are placed in portal Under the project component-description.md In file -->
portal->component-description.md 
  1. Component demo address:
<!-- 
  erp All encapsulated components in the project demo All put in frame Under the project demo Folder
  demoComponent.vue File Representation Component demo Instances to see if there are components you need
  demoForm.vue Express form Form component
  invoiceAdd.vue form Form Components, Generated by Code Generator
  invoiceList.vue table List Components, Generated by Code Generator
-->
frame -> demo -> demoComponent.vue
              -> demoForm.vue
              -> invoiceAdd.vue
              -> invoiceList.vue 
  1. Global Common Style View
<!-- 
  The global public demonstration in erp system is placed in SRC - > CSS file - > public - > commonBase. SCSS under portal project 
  commonBase.scss Global Common Style, no need to introduce, take it over and use it directly
  commonBase.css is a static resource file used in commonBase.html

  How about the specific style, you can open commonBase.html directly in the browser
-->

vue.config.js

const webpack = require('webpack')
const merge = require('webpack-merge') // base64
const APP_NAME = require('./package.json').name //entry name
const InsertScriptPlugin = require('./scripts/InsertScriptWebpackPlugin') //Insert script plug-in
const PROXY = require('./config/proxy') //Subproject url proxy profile
const modules = require('./config/modules') //Subproject configuration file to load
const path = require('path')
// Optimization plug-in
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, // Does cssSourceMap, TODO?? [xsw] Packaging should be set to false???

  /**
   * Type: Object
   * All webpack-dev-server options are supported
   * Some values, such as host, port, and https, may be overwritten by command-line parameters
   * Some, such as publicPath and historyApiFallback, should not be modified because they need to synchronize with the development server's baseUrl to ensure normal operation.
   */
  devServer: {
    port: 18080, //Project port
    proxy: PROXY, //This tells the server to proxy any unknown requests (requests that do not match static files) to the url configured in PROXY
    disableHostCheck: true, //Turn off host detection (configure this to be accessible via domain name)
    compress: true, // Code compression
  },

  /**
   *  Configure other options for Webpack
   *  warning
      Some webpack options are based on values in vue. config. js, so they cannot be modified directly. For example, you should modify the output Dir option in vue. config. JS rather than the output.path; you should modify the baseUrl option in vue. config. JS rather than the output.publicPath option. This is because the values in vue.config.js are used in multiple places in the configuration to ensure that all parts work together.
   */

  configureWebpack: {
    //vue must be introduced here
    externals: {
      vue: 'Vue',
    },
    // Separate plug-in
    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 }),
      // Start report 
      new BundleAnalyzerPlugin({
        generateStatsFile: true,
        statsOptions: { source: false }
      }),
      // Removal of i18n from moment
      new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /zh-cn/),
      // Declare the minimum volume of production environment
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('production')
        }
      }),
      // Compression at the code level
      new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i,
        threshold: 0, // Only resources larger than this value are processed
        minRatio:0.8, // Only resources with compression rates less than this value will be processed
        deleteOriginalAssets: false // delete original file
      }),
      // Removal of redundant 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 => {
    //path alias
    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 related code
    // image-webpack-loader for image compression optimization
    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()
  },

  // To use the scss variables globally, Mixin is introduced here (Note: This kind of scss file requires one copy for each project and one copy for each project for this configuration)
  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";
        `
      }
    }
  }
}

Tags: Front-end npm Webpack Vue sass

Posted on Thu, 10 Oct 2019 08:25:30 -0700 by ponsho