繁体   English   中英

转译 ES6 嵌套的 node_modules 依赖的顶级 node_modules 依赖

[英]Transpile ES6 nested node_modules dependency of the top level node_modules dependency

我在 ES6 格式的node_modules中有一个依赖项,它的嵌套 node_modules 依赖项也是 ES6 格式。

我设法将顶级依赖项(例如dependencyA )包含到 babel 配置中并将其转换为项目代码。 但是如果这个依赖有其他ES6格式的依赖怎么办呢? 那么:如何配置 babel/webpack 来转换嵌套的node_modules依赖项?

这是结构

Project (Babel/Webpack/Typescript)
 - node_modules
   - dependencyA (ES6) // ok, added top level ES6 dep to babel transpilation
     - node_modules
       - nested_dependency (ES6) // what to do with that?

我应该 go 更深入并手动包含这样一个嵌套的 node_modules package 吗?

例如。 babel.config.js

const path = require('path');
module.exports = function (api) {
  api.cache(true);
  return {
    sourceMaps: true,

    include: [
      path.resolve('src'),
      path.resolve('node_modules/dependencyA'), // ok, added top level ES6 dep

      path.resolve('node_modules/dependencyA/node_modules/nested_dependency'), // should I do that?
    ],
    presets: [
      '@babel/preset-env',
      '@babel/preset-react',
      '@babel/preset-flow',
      '@babel/preset-typescript',
    ],
  .....

它看起来有点多余。 有没有办法处理它? 谢谢你的帮助!

有一种很酷的方法可以使用 regex negative look a head 来做到这一点。

语法是: X(?!Y) ,意思是“搜索 X,但前提是后面没有 Y”。

假设您知道要转译哪个 node_modules deps(在第一层)。

您可以指定此正则表达式/(dep1|dep2)[\\/](?..*node_modules)/

const PATH_DELIMITER = '[\\\\/]'; // match 2 antislashes or one slash
const safePath = (module) => module.split('/').join(PATH_DELIMITER);

const generateIncludes = (modules) => {
  return [
    new RegExp(`(${modules.map(safePath).join('|')})$`),
    new RegExp(`(${modules.map(safePath).join('|')})${PATH_DELIMITER}(?!.*node_modules)`)
  ];
};

const generateExcludes = (modules) => {
  return [
    new RegExp(
      `node_modules${PATH_DELIMITER}(?!(${modules.map(safePath).join('|')})(${PATH_DELIMITER}|$)(?!.*node_modules))`
    )
  ];
};

此代码取自next-transpile-modules

这 2 个函数应该使用您需要转换的模块数组来调用,并将其传递给includeexclude

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM