Babel 不是 运行 通过 Webpack 加载器从 `node_modules` 导入

Babel not running on imports from `node_modules` via Webpack loader

我无法让 Webpack 访问 运行 babel node_modules 中的文件。特别是,我正在尝试使用自定义 webpack 加载程序转换 .svg 文件(来自 FontAwesome 或其他 .svg 来源),然后将其传递给 Babel 以转换为 JSX。

在我尝试过的许多不同配置中,问题通常表现为:

1。 Unexpected token

Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
<svg ...></svg>

这表明自定义加载器和 babel 都没有被应用,即文件只是在没有任何加载器的情况下被传递。

2。 Syntax Error

SyntaxError: /Users/bmh/Repos/bug-reports/node_modules/icon/ad.svg: 
  Unexpected token (2:20)
1 |
2 |     const element = <div>hey</div>;

这表明自定义加载器正在工作(因为出于测试目的,它被硬编码为 <div>hey</div>),但未调用后续的 babel-loader

.svg 不在 node_modules 中时,不会 出现问题,这意味着自定义加载器和 babel-loader 正在按预期工作。 webpack 或 babel 决定不将 babel 转换应用于 node_modules 中的文件,目前尚不清楚如何解决此问题。

我发现的一个似乎有分量的建议是向 webpack module.rules 提供 includeexclude 参数,但我尝试的各种排列似乎没有工作。

重现

存储库:https://github.com/brianmhunt/bug-reports/tree/jsx-svg-import

$ git clone git@github.com:brianmhunt/bug-reports.git`
$ git checkout jsx-svg-import
$ make

作为detailed in bug #736 of babel-loader:

... convert .babelrc to babel.config.js with same configuration, babel-loader [works] as expected.

解释是:

... because .babelrc doesn't "leak" across different packages (delimited by package.json)