How to optionally process code in node_modules with babel-loader in webpack?

旧街凉风 提交于 2019-12-23 18:38:55

问题


This is a follow up from this answer.

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',
                    ...
                }
            }
        ]
    },
    ...
}

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',
                    ...
                }
            }
        ]
    },
    ...
}

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?


回答1:


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.



来源:https://stackoverflow.com/questions/53016083/how-to-optionally-process-code-in-node-modules-with-babel-loader-in-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!