如何从 webpack 的加载程序中排除嵌套的 node_module 文件夹

how to exclude nested node_module folders from a loader in webpack

下面的exclude: '/node_modules/'是只排除同目录下的node_modules文件夹,还是也会排除嵌套的node_module文件夹?如果不是:我如何调整它以排除所有 node_module 文件夹?

module: {
    loaders: [
        { test: /\.ts$/, loader: 'ts-loader',exclude: '/node_modules/' } 
    ]
},

文件结构:

/general
/node_modules
/mod1
     /src
     /node_modules
/mod2
     /src
     /node_modules

The documentation

A condition may be a RegExp, a string containing the absolute path, a function(absPath): bool, or an array of one of these combined with “and”.

因此,在此基础上,您可以尝试构建适合您情况的 RegExp。

我个人更喜欢使用 include 而不是 exclude,因为白名单比黑名单更容易维护。至少这样你的控制力更强了。

按照这种思路,您可以完全跳过 exclude 问题并构建如下规则:

include: [
    path.resolve(__dirname, 'general'),
    path.resolve(__dirname, 'mod1/src'),
    path.resolve(__dirname, 'mod2/src')
]

当然,如果你有更复杂的结构,你最终可能会把两者结合起来。一条规则指向 exclude node_modules 一条规则指向 include 您要查看的目录。

如果您的问题仅与 TypeScript 文件有关,您可以利用 'ts-loader' 将在编译时使用您的 tsconfig.json 文件这一事实。您可以在此处定义要排除的路径。