问题
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