webpack babel jsnext:main 和依赖转译

webpack babel jsnext:main and dependencies transpiling

上周我打开了以下问题,但似乎没有人知道答案:

我真的不明白 webpack / babel-loadernode_modules 中转译依赖项的当前状态是什么,谁能解释一下?我试图坚持在任何地方打开的每个问题。

  1. webpack / babel-loader 正在转译 jsnext:main 文件吗?
  2. 如果是,webpack / babel-loader 是否在 node_modules 中转译 jsnext:main 文件,即使 node_modules 在排除键中?

我的情况:

rules: [{
    test: /\.(js|mjs)$/i,
    exclude: [/node_modules/],
    use: [{
        loader: 'babel-loader', //settings specified in package.json
    },{
        loader: 'eslint-loader', //settings specified in package.json
    }
}]

在我的依赖中 package.json 我试过:

"main": "index.js", <= not working (not transpiled)
"jsnext:main": "index.js", <= not working (not transpiled)
"module": "index.js", <= not working (not transpiled)

如果不删除 exclude: [/node_modules/], 两者都无法工作,但是由于无限的编译时间,这不能用于任何中型到大型项目。

但是然后:为什么是 https://github.com/lodash/lodash/blob/es/package.json any different from my https://github.com/damianobarbati/react-create-app/blob/master/package.jsonlodash-es 即使在 node_modules 中也被转译(并被排除在外)但我的 react-create-app 不是:救命!

当您从规则中排除 node_modules 时,babel-loader 不会转译 node_modules 中的任何内容。 jsnext:mainmodule 等字段与 loaders/rules 无关。当一个包被导入时,webpack 根据 resolve.mainFields and then it will check which rules it should apply to that file. Usually these files are already transpiled, except that they contain ES modules (see Rollup - pkg.module).

决定它应该使用什么文件。

如果您想转换任何具有 modulejsnext:main 字段的模块,您可以使用来自 Jason Miller developit/transpile-esnext-modules.js 的规则来确定该模块是否应该被包含或不是(includeexclude 也接受函数)。