如何使用babel-loader转译node_modules模块?

问题描述 投票:0回答:2

问题:我想为旧版浏览器(> = IE10)的网站构建捆绑文件。

当我使用

babel 7.x
使用
babel-loader
转译代码时,我的转译代码会在旧版 Internet Explorer 11 上抛出错误,因为看起来
node_modules
模块默认情况下不会再转译?

问题: 如果包作者尚未转译我的所有

node_module
模块,如何确保它们都将被转译?

使用 babel-loader 的 webpack.config.js

// webpack.config.js
rules: [
    {
        test: /\.(js|jsx)$/,
        use: [
            {
                loader: 'babel-loader',
            },
        ],
        exclude: [],
    },
],

使用 babel 7.x 的 babelrc.js 配置

// .babelrc.js
module.exports = function(api) {
    const presets = [
        [
            '@babel/preset-env',
            {
                useBuiltIns: 'usage',
                ignoreBrowserslistConfig: true,
                targets: {
                    node: 8,
                    browsers: [
                        'last 3 versions',
                        '> 1% in DE',
                        'Explorer >= 10',
                    ],
                },
            },
        ],
        '@babel/preset-react',
    ];

    const plugins = [
        // ...
    ];

    return {
        presets,
        plugins,
    };
};

更新1:

这是 babel 的问题。我的 babel 配置名为

.babel.rc
,babel 7 默认设置是查找名为
babel.config.js
的配置文件,请参阅here

因此,将 babel 配置文件从“.babel.rc”重命名为“babel.config.js”后,我可以在here描述的“webpack.config.js”中应用解决方案,以使用以下命令转换未转换的“node_modules”包:这样的解决方案:

// webpack.config.js
rules: [
    {
        test: /\.(js|jsx)$/,
        use: [
            {
                loader: 'babel-loader',
            },
        ],
        // Exclude the untransformed packages from the exclude rule here
        exclude: /node_modules\/(?!(MY_MODULE|ANOTHER-ONE)\/).*/, 
    },
],

问题: 感觉像是解决方法,但是有没有更方便的方法来处理此类问题?我只是假装在不久的将来会有越来越多未转换的包(在此讨论之后),我们是否总是必须手动将其包名称放入 webpack 的

exclude
规则中?

javascript webpack node-modules babeljs babel-loader
2个回答
5
投票

问题:感觉像是解决方法,但是有没有更方便的 如何处理此类问题?我只是假装会有越来越多 在不久的将来外面未转换的包(在此之后 讨论)我们是否总是需要手动输入包名称 在 webpack 的排除规则中??

您可以使用

are-you-es5
等模块自动创建例外列表或测试:https://www.npmjs.com/package/are-you-es5

此外,如果指向您的

eslint-plugin-compat
,类似
node_modules
之类的内容也可能会警告您出现问题:https://www.npmjs.com/package/eslint-plugin-compat

但它并不完美。我认为在一般的生产设置中,您应该在添加软件包之前了解您添加的软件包,或者进行一些自动化测试,以便在 IE11 对您的项目至关重要的情况下捕获浏览器错误。

我知道这并不总是可能的,但我强烈建议将 IE11 及更低版本推向一些较低层的支持。使用现代 JS 的同时,仍然维护 IE11 及以下版本是非常困难的。


0
投票

我知道这是一个老问题,但最近我花了相当长的时间来解决同样的问题,所以我也想分享我的经验。

首先,

exclude: /node_modules\/(?!(MY_MODULE|ANOTHER-ONE)\/).*/
仅适用于*nix,但不适用于window,因为window使用
/
作为路径,因此使用正则表达式的通用解决方案是
exclude: /node_modules(?!(\/|\\)MY_MODULE|ANOTHER-ONE)/

其次,使用负向先行正则表达式确实感觉很尴尬,并且 https://github.com/babel/babel-loader#some-files-in-my-node_modules-are-not-transpiled-for-ie-11 有一个更好的方法

exclude: {
      and: [/node_modules/], // Exclude libraries in node_modules ...
      not: [
        // Except for a few of them that needs to be transpiled for IE
        /unfetch/,
        /d3-array|d3-scale/,
        /@hapi[\\/]joi-date/,
      ]
    },
© www.soinside.com 2019 - 2024. All rights reserved.