栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

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

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

本文我们来看一下官方的这个 @vue/cli-plugin-babel

先看一下源码文件:

generator.jsindex.js

核心的有 2 个文件,我们主要第一个 index.js,最外层结构多是插件式的标准结构:

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

这里因为我们要扩展 webpack 的配置,所以使用了:api.chainWebpack

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

我们先执行 vue inspect --rule js 看一下最终生成的配置:

{  test: /.jsx?$/,  exclude: [    function () {  }
  ],  use: [    
    {      loader: 'cache-loader',      options: {        cacheDirectory: '/Usersnode_modules/.cache/babel-loader',        cacheIdentifier: '2f4347b9'
      }
    },    
    {      loader: 'babel-loader'
    }
  ]
}

对照着这个我们来写相对会简单一点:

1、配置 module、 rule 和 test

注意这里的 rule 是 js,也就是我们之前 vue inspect 用到的

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

2、配置 exclude

通过 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-serviceconst 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 transpileif (options.transpileDependencies.some(dep => filepath.match(dep))) {  return false}// Don't transpile node_modulesreturn /node_modules/.test(filepath)

3、配置 use

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

4、根据条件判断是否增加 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')



作者:dailyvuejs
链接:https://www.jianshu.com/p/19fa9a369666


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/240494.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号