Home >Web Front-end >Vue.js >Vue-cli and Webpack packaging release optimization guide

Vue-cli and Webpack packaging release optimization guide

WBOY
WBOYOriginal
2023-06-09 16:05:451058browse

With the continuous development of Web front-end technology, Vue.js has become a very popular front-end framework. Vue-cli and Webpack in Vue.js have also become necessary supporting tools as build tools. When developing projects, we usually use Vue-cli to build the application framework and use Webpack to package and publish the project. However, in the process of packaging and releasing large projects, due to the large size of the project, problems such as slow compilation speed, large packaging volume, and slow access speed may occur. In order to avoid these problems, this article will introduce Vue-cli and Webpack packaging. Release optimization guide to help developers better optimize the release effects of large projects.

1. Vue-cli project optimization

  1. Introducing third-party components on demand

During the development process, we usually use jQuery, Bootstrap, Third-party libraries such as Echarts, but introducing the entire library may cause problems such as excessive packaging size and slow access speed. Therefore, we can use the babel-plugin-component plugin to introduce on-demand.

Set in babel.config.js:

plugins: [
  ['component', {
    libraryName: 'element-ui',
    styleLibraryName: 'theme-chalk'
  }]
]

Taking Element-ui as an example, use the plug-in to introduce the library on demand, you can Greatly reduce packaging volume.

  1. Configuring Webpack properties

We can modify the configuration properties of Webpack by modifying the vue.config.js file. The following are some commonly used Webpack attribute configuration methods:

// 修改输出文件名格式
output: {
  filename: '[name].[hash].js'
}

// 修改 publicPath
publicPath: process.env.NODE_ENV === 'production' ?
  '/production-sub-path/' : '/'

// 压缩代码
uglifyOptions: {
  compress: {
    warnings: false,
    drop_console: true,
    drop_debugger: true,
    dead_code: true
  }
}

// 配置 externals,将大型的第三方库从打包代码中剥离
externals: {
  'vue': 'Vue',
  'jquery': 'jQuery',
  'bootstrap': 'Bootstrap',
  'echarts': 'echarts',
  'moment': 'moment'
}

// 使用 Webpack-bundle-analyzer 查看打包后的各个模块的大小
configureWebpack: {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}

2. Webpack optimization

  1. Use multi-threaded build

Using multi-threaded build can greatly To improve packaging speed, you can use the happypack plug-in to implement multi-threaded builds. To use this plug-in, you need to install happypack first:

npm install happypack -D

Then modify the original configuration file:

module: {
  rules: [
    {
      test: /.js$/,
      loader: 'babel-loader'
    },
    ...
  ]
}

to:

const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });

module: {
  rules: [
    {
      test: /.js$/,
      exclude: /node_modules/,
      loader: 'happypack/loader?id=happyBabel'
    },
    ...
  ]
},
plugins: [
  new HappyPack({
    id: 'happyBabel',
    loaders: ['babel-loader'],
    threadPool: happyThreadPool,
    verbose: true
  })
]

Use ## here #happypack Plugin to enable multi-threaded builds.

    Using DllPlugin and DllReferencePlugin technology
DllPlugin and DllReferencePlugin technology mainly packages some libraries that do not change frequently into a lib file, so that each time it is packaged, There is no need to package these library files, you only need to use DllReferencePlugin to introduce them later.

Usage:

    Configure DllPlugin first:
  1. const path = require('path');
    const webpack = require('webpack');
    const dllPath = 'static/dll';
    
    module.exports = {
      entry: {
        vendor: ['vue', 'vue-router', 'vuex', 'axios', 'lodash'] // 需要单独打包的库
      },
      output: {
        path: path.join(__dirname, `../${dllPath}`),
        filename: '[name].dll.js',
        library: '[name]_[hash]'  // 暴露全局变量,避免前后两次打包,库名字变更
      },
      plugins: [
        new webpack.DllPlugin({
          name: '[name]_[hash]',
          path: path.join(__dirname, `../${dllPath}`, 'manifest.json')
        })
      ]
    };
    Execute packaging:
  1. cross-env NODE_ENV=production webpack --config ./build/webpack.dll.js --progress --hide-modules
    Use
  1. 3f1c4e4b6b16bbbd69b2ee476dc4f83a in index.html to introduce the generated library file:
  2. <script src="<%= BASE_URL %>static/dll/vendor.dll.js"></script>
    Configure DllReferencePlugin:
  1. const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');
    const path = require('path');
    
    plugins: [
      new webpack.DllReferencePlugin({
        context: __dirname,
        manifest: require(path.join(__dirname, './static/dll/manifest.json'))
      }),
      new AddAssetHtmlWebpackPlugin({
        filepath: path.resolve(__dirname, './static/dll/*.dll.js')
      })
    ]
This plug-in can automatically introduce the generated Dll file into the page.

Summary:

Through the above methods, we can optimize Vue-cli and Webpack to make our project packaging smaller and faster. Of course, the above method is not a silver bullet, and the specific optimization method needs to be adjusted according to the specific conditions of the project. I hope this article can be helpful to everyone when packaging and publishing projects.

The above is the detailed content of Vue-cli and Webpack packaging release optimization guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn