手寫個人 VUE-CLI

webpack學習的大體過程在此記錄一下。
css

先建立一份 vue-cli 做爲參考。cli.vuejs.org/zh/guide/in…html

$ yarn global add @vue/cli
$ vue -V // 查看版本
$ vue init webpack vue-cli
複製代碼

而後建立 my-vue-cli 初始化項目結構,添加.gitignore等。vue

$ npm init
$ git init
複製代碼

1. 初始化webpack

webpack.docschina.org/guides/inst…node

// webpack 4.x+
$ yarn add webpack webapck-cli -D
複製代碼

2. 添加項目結構

  • 入口文件:src/main.js, 在main.js中隨便寫點js。
  • html模版文件:index.html
  • webpack配置文件: webpack.config.js

3. webpack 基礎配置

// webpack.config.js
const path = require('path')

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].[hash:8].js'
  }
}
複製代碼
// package.json
{
    "scripts": {
        "build": "webpack",
    }
}
複製代碼

$ yarn build, 會生成dist/app.**.js, 將app.**.js在瀏覽器 console 中運行試試。(webpack 命令會自動查找 webapck.config.js 並執行)。webpack

4. 使用devServer, HtmlWebpackPlugin

webpack-dev-servergit

$ yarn add webpack-dev-server -D
$ yarn add html-webpack-plugin -D
複製代碼
plugins: [
    new HtmlWebpackPlugin({ template: path.resolve(__dirname, './index.html') })
  ],

  devServer: {
    // https: true,
    open: true,
    host: '0.0.0.0',
    port: 8000,
    disableHostCheck: true,
    hot: true,
    proxy: {//配置跨域,訪問的域名會被代理到本地的3000端口
      '/api': 'http://localhost:3000'
    }
  }
複製代碼

5. 轉譯ES六、ES7 使用 babel-loader

webpack.docschina.org/loaders/bab…
// 注意 babel-loader@7 與 babel-core@6 配套使用;babel-loader@8 與 babel-core@7 配套使用。github

$ yarn add babel-loader babel-core babel-preset-env babel-preset-stage-2 -D
$ yarn add babel-plugin-transform-runtime babel-runtime -D
複製代碼

添加 .babelrc 文件web

{
  // presets 告訴 babel 源碼使用了哪些新的語法特性。
  "presets": [
    [
      "env",
      {
        "modules": false
      }
    ],
    "stage-2"
  ],
  // 生成的文件中,不產生註釋, 會使 /* webpackChunkName: 'helloWorld' */ 失效
  // "comments": false,
  "plugins": [
    [
      // babel-plugin-transform-runtime 減小冗餘代碼,依賴 babel-runtime
      "transform-runtime",
      {
        "helpers": true,
        "polyfill": true,
        "regenerator": true,
        "moduleName": "babel-runtime"
      }
    ]
  ],
  "env": {
    // 測試環境,test 是提早設置的環境變量,若是沒有設置BABEL_ENV, 則使用NODE_ENV,若是都沒有設置默認就是development
    "test": {
      "presets": [
        "env",
        "stage-2"
      ],
      // instanbul是一個用來測試轉碼後代碼的工具
      "plugins": [
        "istanbul"
      ]
    }
  }
}
複製代碼
// webpack.config.js
module.exports = {
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                loaders: [
                    {
                      loader: 'babel-loader',
                      options: {
                        cacheDirectory: true,
                      },
                    },
                  ],
            },
        ]
    }
}
複製代碼

6. 接入less、postcss

$ yarn add less less-loader css-loader style-loader -D
$ yarn add postcss-loader autoprefixer -D
複製代碼

添加.postcssrc 文件。vue-router

{
  "plugins": {
    "autoprefixer": {
      "browsers": ["IOS>=7", "Android>=4.1", "IE>=9"],
    }
  }
}

複製代碼

7. 識別 .vue 文件

$ yarn add vue-loader vue-template-compiler -D
$ yarn add vue
複製代碼
resolve: {
    alias: {
      vue$: 'vue/dist/vue.runtime.esm.js'
    },
  },
複製代碼

8. 對文件使用 url-loader(基於file-loader + limit功能)

$ yarn add url-loader -Dvue-cli

{
  test: /\.(jpg|jpeg|gif|png|svg|webp)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 8192,
        name: 'assets/images/[hash:8].[ext]',
      }
    }
  ]
},
{
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        name: 'assets/fonts/[hash:8].[ext]',
      }
    }
  ]
},
複製代碼

9. 接入 vue-router

$ yarn add vue-router

// 添加別名
resolve: {
    alias: {
      "@": path.resolve(__dirname, 'src')
    },
  },

// 按需加載, 注意.babelrc中: "comments": false,會使 /* webpackChunkName: 'helloWorld' */ 失效
const HelloWorld = () => import(/* webpackChunkName: 'helloWorld' */ '@/components/HelloWorld');
複製代碼

10. 使用 clean-webpack-plugin

const CleanWebpackPlugin = require('clean-webpack-plugin');
plugins: [
  new CleanWebpackPlugin(), // 多版本共存模式時 必需要取消這個插件
]
複製代碼

11. 加入eslint + pritter + pre commit hook 約束代碼提交

$ yarn add babel-eslint eslint eslint-config-standard eslint-plugin-html eslint-plugin-promise eslint-plugin-standard eslint-plugin-import eslint-plugin-node -D
$ yarn add eslint-loader -D
$ yarn add prettier -D --exact
$ yarn add eslint-plugin-prettier eslint-config-prettier eslint-plugin-vue -D
// lint-staged、 husky插件,這樣再每次 commit 代碼的時候都會格式化一下。
$ yarn add lint-staged husky@next -D
複製代碼
// 添加 .eslintrc.js
// 添加.prettierrc

// package.json
// pre-commit 約束代碼提交
"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
"lint-staged": {
    "*.{js,json,css,md,vue}": ["prettier --write", "git add"]
  }

// webpack.config.js
module: {
  rules: [
     {
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        exclude: /(node_modules|bower_components)/,
      },
  ]
}
複製代碼

12. 使用 CopyWebpackPlugin

// copy custom static assets
new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, './static'),
    to: 'static',
    ignore: ['.*'],
  },
]),
複製代碼

優化

1. 區分環境

不一樣環境,使用不一樣配置插件等。 $ yarn add cross-env -D

// package.json
scripts: {
  "build": "cross-env NODE_ENV=production webpack",
}

// 使用
porcess.env.NODE_ENV
複製代碼

2. 使用mode

webpack.docschina.org/concepts/mo… webpack4+ mode簡化了許多配置。

const mode = process.env.NODE_ENV || 'development'

module.exports = {
  mode: mode,
}
複製代碼

3. 輸出文件版本控制

開發環境的 --hot 不能使用contenthash、chunkhash

const chunkhash = isDev ? '[name].[hash:8].js' : '[name].[chunkhash:8].js'
const contenthash = isDev ? '[name].[hash:8].css' : '[name].[contenthash:8].css'

output: {
  path: path.resolve(__dirname, './dist'),
  filename: chunkhash,
  chunkFilename: chunkhash,
  publicPath: '/',
},
複製代碼

4. 生產環境抽離每個 chunk 的 css 使用 MiniCssExtractPlugin

module: {
  rules: [
    {
      test: /\.(css|less)$/,
      use: {
        loader: isDev ? 'style-loader' : MiniCssExtractPlugin.loader
      },
    }
  ]
}
plugins: [
  new MiniCssExtractPlugin({
      filename: contenthash,
      chunkFilename: contenthash,
    }),
]
複製代碼

5. 分離第三方插件,持久化緩存

webpack.docschina.org/configurati… $ yarn add uglifyjs-webpack-plugin

optimization: {
  runtimeChunk: {
    name: 'manifest',
  },
  splitChunks: {
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        chunks: 'all',
        name: 'vendor',
      },
    },
  },
  minimizer: [
    new UglifyJsPlugin({
      cache: true,
      parallel: true,
      sourceMap: true,
    }),
    new OptimizeCSSAssetsPlugin(),
  ],
},
複製代碼

6. 使用可視化分析 BundleAnalyzerPlugin

// package.json
scripts: {
  "analyz": "NODE_ENV=production npm_config_report=true npm run build"
}

// webpack.config.json
plugins: [
  ...(process.env.npm_config_report ? [new BundleAnalyzerPlugin()] : []),
]
複製代碼

3. 優化構建速度

1. 縮小文件搜素範圍

2. 生成動態連接庫 使用DllPlugin(將第三方插件只編譯一次)

3. 利用 CUP 多核, 使用 HappyPack 加快 loader 轉換

webpack 構建流程中最耗時的就是 Loader 轉換,js 單線程只能對文件一個一個的處理,HappyPack 原理就是將這部分任務,分解到多個進程,減小構建時間。

大中型項目中,使用 happypack 才能看到比較明顯的構建速度提高。

// 見 git 記錄"使用happypack"
複製代碼

4. 利用 CUP 多核, 使用 ParalleUglifyPlugin 加快 UglifyJS 的壓縮。

new ParallelUglifyPlugin({
        uglifyJS: {
          output: {
            // 最緊湊輸出
            beautify: false,
            // 刪除全部註釋
            comments: false,
          },
          compress: {
            drop_console: !isDev,
            collapse_vars: true,
            reduce_vars: true,
          },
        },
      }),
複製代碼

4. 編寫 Loader

webpack.docschina.org/contribute/…

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'vue-loader',
            options: {
              loaders: {
                // happy 不支持 vue-loader, 將js 交由 happypack
                js: 'happypack/loader?id=babel',
              },
            },
          },
          {
            // 爲每一個 vue 文件 添加 ~@/assets/less/variable.less, 避免人工每次導入。
            loader: 'less-auto-import-loader',
            options: {
              url: '~@/assets/less/variable.less',
            },
          },
        ],
      },
    ]
  }
  resolveLoader: {
    // 增長 loader 的查找範圍
    modules: ['node_modules', './loaders/'],
  },
}

複製代碼

5. 編寫 Plugin

***重點是***找到合適的事件點去完成功能。compiler 鉤子

// EndWebpackPlugin webpack構建成功或失敗後執行回調
class EndWebpackPlugin {
  constructor(doneCallback, failCallback) {
    this.doneCallback = doneCallback
    this.failCallback = failCallback
  }
  apply(compiler) {
    compiler.plugin('done', (stats) => {
      this.doneCallback(stats)
    })
    compiler.plugin('failed', (err) => {
      this.doneCallback(err)
    })
  }
}

// webpack.config.js
const EndWebpackPlugin = require('end-webpack-plugin');
plugins: [
  new EndWebpackPlugin((stats) => {}, (err) => {})
]
複製代碼

github: github.com/lizhuang93/…
webpack官網: webpack.docschina.org/concepts/

相關文章
相關標籤/搜索