从Webpack的require.context中排除文件

12

我正在尝试使用Webpack的require.context将所有应该被我的Istanbul报告工具覆盖的文件包含进来。

我希望包含/需要所有app文件夹下没有.test.js扩展名的文件。

// internals/testing/test-bundler.js
const context = require.context('../../app', true, /^.*(?!(\.test|internals.*))\.js$/);
context.keys().forEach(context);

我的文件结构是:

app/components/
app/containers/
app/decorators/
app/orm/
app/pages/
app/store/
app/tests/
app/utils/
app/app.js
app/reducers.js
app/routes.js
internals/testing/test-bundler.js
很明显我的正则表达式不起作用了,因为在覆盖率报告中我看到所有的.test.js文件甚至是internals/testing/test-bundler.js文件。我做错了什么?
4个回答

19

在使用负向预查时,您需要注意它的拒绝部分是哪一部分。如果您在第一个正斜杠后立即使用,它将正常工作。

除了直接在斜杠后面加上test以外,您还希望在斜杠后面拒绝.*test

/^(?!internals).*\/(?!.*test).*\.js$/

更具体地说,不允许在路径名中包含internals
也不要以test.js结尾:

^(?!.*(?:internals|test.js$)).*\.js$

使用他的示例路径进行测试,你的答案只返回了 app/app.js - Veverke
它将返回任何目录中的路径,但不包括 internals/*。并且它们在第一个斜杠后面不会有 test。因此,在这种意义上,test/internals.js 仍然可以通过。但是这在正则表达式中很容易更改。 - LukStorms
这是正确的,但要小心,它仍然非常慢,对于大型代码库可能会导致内存泄漏。 - Luca Colonnello

0

即使从require.context中排除node_moduleswebpack仍会递归查找目录,这非常耗时。我在类似情况下遇到了内存溢出的问题。

我认为应该有更好的方法不为每个模块安装node_modules。而是将node_modules保存在其他地方,并在wepback module.resolve中指定位置。将源代码和依赖项分开保存。


这也是我注意到的,特别是在使用pnpm monorepos时,每个包都有独立的node_modules,而不是依赖于顶层node_modules文件夹的hoisting。 - Luca Colonnello

0

我已经确保了更有用的回归,以排除具有后缀*-spec.js或位于test文件夹内的文件

/^((?<!test\/).(?!-spec))+\.js$/.test('a.js'); // => true
/^((?<!test\/).(?!-spec))+\.js$/.test('a-spec.js'); // => false

/^((?<!test\/).(?!-spec))+\.js$/.test('lib/a.js'); // => true
/^((?<!test\/).(?!-spec))+\.js$/.test('lib/a-spec.js'); // => false

/^((?<!test\/).(?!-spec))+\.js$/.test('lib/test/a.js'); // => false
/^((?<!test\/).(?!-spec))+\.js$/.test('lib/test/a-spec.js'); // => false
/^((?<!test\/).(?!-spec))+\.js$/.test('test/lib/a.js'); // => false
/^((?<!test\/).(?!-spec))+\.js$/.test('test/lib/a-spec.js'); // => false

-1

你可以考虑使用简单的filter过滤路径。

示例:

var paths = [
'app/components/',
'app/containers/',
'app/decorators/',
'app/orm/',
'app/pages/',
'app/store/',
'app/tests/',
'app/utils/',
'app/app.js',
'app/reducers.js',
'app/routes.js',
'internals/testing/test-bundler.js',
'app/blablabla.test.js'
];

var result = paths.filter(function(e,i){
   return (e.startsWith('app/') && !e.endsWith('.test.js'))
});

for(var i = 0; i < result.length; i++)
   console.log(result[i]);
  


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接