[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')
相关文章
相关标签/搜索