如何在webpack中使用babel-loader选择性地处理node_modules中的代码? [英] How to optionally process code in node_modules with babel-loader in webpack?

查看:2091
本文介绍了如何在webpack中使用babel-loader选择性地处理node_modules中的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此答案的跟进。

我有一些第三方代码(反应组件),我捆绑为ES模块(使用 pkg.module 入口点)。这很好用(你得到模块连接和树摇动),但是包含的代码没有用babel编译,因为按照大多数配置示例,我在babel中排除 node_modules - 我的webpack配置的loader部分如下所示:

I have some 3rd party code (react components) that I bundle as ES modules (using the pkg.module entry point). This works great (you get module concatenation and tree shaking), but the included code isn't transpiled with babel because, following most config examples, I exclude node_modules in the babel-loader section of my webpack config like this:

{
    ...
    module: {
        rules: [
            {
                exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    ...
                }
            }
        ]
    },
    ...
}

因此,当我运行webpack时,我收到意外的令牌错误。基于链接的答案,我从使用 exclude 切换到 include ,以选择从<$引入一些包c $ c> node_modules 这样:

So, I get unexpected token errors when I run webpack. Based on the linked answer, I switched from using an exclude to an include to optionally bring in some packages from node_modules like this:

{
    ...
    module: {
        rules: [
            {
                include: [/node_modules\/@my-scope/, /src/],
                use: {
                    loader: 'babel-loader',
                    ...
                }
            }
        ]
    },
    ...
}

这似乎对我有用(当我运行webpack时没有更多,意外的令牌错误),但我'我不是100%肯定它正在做我认为的事情。

This seems to be working for me (no more, unexpected token errors when I run webpack), but I'm not 100% sure it's doing what I think it is.

这个解决方案看起来是否合适?有没有更好的方法?

Does this solution look right? Is there a better way?

推荐答案

解决方案对我来说没问题。如果include开始变得复杂,你可以用函数替换它并使用逻辑来过滤。

The solution looks ok to me. If the include begins to get complex, you could replace it with a function and use logic to filter there.

这篇关于如何在webpack中使用babel-loader选择性地处理node_modules中的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆