[Vue CLI 3] 插件解析之 @vue/cli-plugin-babel

本文咱們來看一下官方的這個 @vue/cli-plugin-babelvue

先看一下源碼文件:node

generator.js
index.js

核心的有 2 個文件,咱們主要第一個 index.js,最外層結構可能是插件式的標準結構:webpack

module.exports = (api, options) => {
  // ...
}

這裏由於咱們要擴展 webpack 的配置,因此使用了:api.chainWebpackweb

api.chainWebpack(webpackConfig => {
  // ...
})

咱們先執行 vue inspect --rule js 看一下最終生成的配置:api

/* config.module.rule('js') */
{
  test: /\.jsx?$/,
  exclude: [
    function () { /* omitted long function */ }
  ],
  use: [
    /* config.module.rule('js').use('cache-loader') */
    {
      loader: 'cache-loader',
      options: {
        cacheDirectory: '/Users/***/node_modules/.cache/babel-loader',
        cacheIdentifier: '2f4347b9'
      }
    },
    /* config.module.rule('js').use('babel-loader') */
    {
      loader: 'babel-loader'
    }
  ]
}

對照着這個咱們來寫相對會簡單一點:babel

一、配置 moduleruletest函數

注意這裏的 rulejs,也就是咱們以前 vue inspect 用到的ui

const jsRule = webpackConfig.module
      .rule('js')
        .test(/\.jsx?$/)

二、配置 excludethis

經過 add 方法插件

.exclude
  .add(filepath => {
    // ...
  })
  .end()

具體的函數:

  • /.vue.jsx?$/
  • options.transpileDependencies

返回 false

這裏的 transpileDependencies 是在 vue.confg.js 中配置的,開發者能夠自行配置
  • /node_modules/
  • cliServicePath

返回 true

if (/\.vue\.jsx?$/.test(filepath)) {
  return false
}
// exclude dynamic entries from cli-service
const cliServicePath = require('path').dirname(require.resolve('@vue/cli-service'))
if (filepath.startsWith(cliServicePath)) {
  return true
}
// check if this is something the user explicitly wants to transpile
if (options.transpileDependencies.some(dep => filepath.match(dep))) {
  return false
}
// Don't transpile node_modules
return /node_modules/.test(filepath)

三、配置 use

.use('cache-loader')
  .loader('cache-loader')
  .options()
  .end()

四、根據條件判斷是否增長 thread-loader

條件以下:用戶在 vue.config.js 中是否配置了 parallel 並且要是 production 環境

const useThreads = process.env.NODE_ENV === 'production' 
&& options.parallel

仍是用 .user.loader

if (useThreads) {
  jsRule
    .use('thread-loader')
      .loader('thread-loader')
}

最後追加了一個 babel-loader

jsRule
  .use('babel-loader')
    .loader('babel-loader')
相關文章
相關標籤/搜索