A vUE project packaged with Webpack 4, referring to the WEBpack configuration of VUE-CLI,

It takes you step by step to implement a vUE packaged project, one step for each commit.

Making the address

Cloning project

git clone [email protected]:naihe138/nvue.git

Install dependencies

npm install or yarn

Initialize the project

Initialize the project, use vue-loader to package. Vue files, html-webpack-plugin to export HTML files. The first step is very simple, we have used the vue – loader and Babel – loader is put. Vue file package, a total of more than 40 lines of code, the build/webpack base. Conf., js file annotation will see understand. +++ indicates omitted code

module.exports = {
  +++
  // module, loader
  module: {
    rules: [{test: /\.vue$/.loader: 'vue-loader'.exclude: /node_modules/.include: resolve('src')}, {test: /\.js$/.loader: 'babel-loader'.exclude: /node_modules/.include: resolve('src')}]} +++}Copy the code

Run webpack – config build/webpack. Base. Conf. Js

2. Pack CSS and images

Take SASS as an example, mini-CSS-extract-plugin is used to extract CSS, and URL-loader is used to process fonts, pictures, audio and other resources. Very simple. The following code, +++ indicates omitted code

+++
module.exports = {
  +++
  // module, loader
  module: {
    rules: [+ + + {test: /\.s? css$/.use: [
          MiniCssExtractPlugin.loader,
          'css-loader'.'sass-loader'] {},test: /.(png|jpe? g|gif|svg)(\? . *)? $/.loader: 'url-loader'.options: {
          limit: 10000.name: 'static/img/[name].[hash:7].[ext]'}} +++]},/ / the plugin
  plugins: [
    +++
    new MiniCssExtractPlugin({
      filename: 'static/css/[name].[hash].css'.chunkFilename: 'static/css/[name].[hash].css'}})]Copy the code

Run webpack – config build/webpack. Base. Conf. Js

Configure hot loading, proxy and other development environment

Set the development configuration through build/config.js. The following comment


const path = require('path')

module.exports = {
  dev: {
    assetsSubDirectory: 'static'.// Static file directory
    assetsPublicPath: '/'.// Relative file path
    proxyTable: {},
    host: 'localhost'.port: '8000'.autoOpenBrowser: false.// Whether to open the browser automatically
    errorOverlay: true.// Browser error message mask layer
    notifyOnErrors: true.Friendly-errors-webpack-plugin is required when compiling errors are reported
    poll: false.useEslint: true.// Use the eslint-loader module cheaply
    showEslintErrorsInOverlay: false.// ESLint browser error indicating mask layer
    devtool: 'cheap-module-eval-source-map'.// Source Maps
    cssSourceMap: true.// css Source Maps
    cacheBusting: false.// Vue debugg prompts}}Copy the code

In webpack.dev.conf.js, the webpack-dev-server plug-in is used to enable the hot reload service. At the same time, the plug-in postCSS-loader that automatically fills the CSS compatible code is configured

To start the service, run NPM run dev or yarn dev

Configure the packaging environment

Set the development configuration through build/config.js. The following comment

const path = require('path'Module.exports = {+++ build: {// HTML template index: path.resolve(__dirname,'.. /dist/index.html'),
    // Paths
    assetsRoot: path.resolve(__dirname, '.. /dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/'// Souce map productionSourceMap for production environment:false,
    devtool: '#source-map', // Enable Gzip compression for static files // If yestrueNPM install --save-dev compression -- webpack-plugin productionGzip:false,
    productionGzipExtensions: ['js'.'css'], // 'NPM run build --report' bundleAnalyzerReport: process.env.npM_config_report}}Copy the code

To package vUE projects, run NPM Run build or YARN Build.

5. Check versioning and optimize packaging output and Eslint Settings

In check-version.js there is NPM command in shelljs, semver module semantics version number, and then in build.js merge webpack.prod.conf.js configuration, and then group formatted output.


// Install NPM
if (shell.which('npm')) {
  versionRequirements.push({
    name: 'npm'.currentVersion: exec('npm --version'),
    versionRequirement: packageConfig.engines.npm
  })
}

// Format output
process.stdout.write(stats.toString({
  colors: true.modules: false.children: false.chunks: false.chunkModules: false
}) + '\n\n')

Copy the code

Use eslint-loader to configure esLint checking and create.eslintrc.js to set rules

{
  test: /\.(js|vue)$/.loader: 'eslint-loader'.enforce: 'pre'.include: [resolve('src')].exclude: /node_modules/.options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
},

Copy the code

Sixth, packaging optimization

1. Add DllPlugin and DllReferencePlugin to package optimized invariant libraries, see webpack.dll.conf.js

2. Use cache-loader to cache loader.

Use UglifyJsPlugin’s PARALLEL to enable multi-threaded packaging


{
    test: /\.vue$/,
    loader: 'vue-loader',
    exclude: /node_modules/,
    include: resolve('src'),
    options: {
      cacheDirectory: resolve('./cache-loader'), // Cache cacheIdentifier:'cache-loader:{version} {process.env.NODE_ENV}'}}, {test: /\.js$/,
    use: isProduction ? [
      {
        loader: 'cache-loader',
        options: {
          cacheDirectory: resolve('cache-loader'), // cache}},'babel-loader'
    ] : 'babel-loader',
    exclude: /node_modules/,
    include: resolve('src')},Copy the code

Run NPM Run DLL and then NPM run build

Github -> github address