我想在 karma 调用的填充文件中动态设置 require.context(path, ...) 的路径(在配置中的文件参数中设置),但不知何故,一旦我使用变量路径,我在 CLI 中收到错误“找不到模块“.””。这很奇怪,因为如果我将非常相同的路径硬编码到调用中,它运行就不会出现问题。又名,如果我这样做的话
var testPath = '../src';
console.log("PATH 2 " + testPath); // ../src
var appContext = require.context(testPath, true, /\.spec\.ts/);
如果我这样做,我会得到一个错误
var appContext = require.context('../src', true, /\.spec\.ts/);
一切都很好。
在完整的 shim 文件中,代码的显示与我在这里编写的完全一样,也就是说 testPath 和 require.context 的定义之间没有其他代码,我只是包含了 console.log 来检查一些莫名其妙的巫毒。
垫片在 karma.conf.js 中按如下方式调用:
module.exports = function (config) {
var _config = {
.....
files: [
{pattern: './karma-test-shim.js', watched: true}
],
preprocessors: {
'./karma-test-shim.js': ['webpack', 'sourcemap']
},
.....
};
config.set(_config);
};
我错过了什么?预处理器对同一个填充程序的调用是否会造成困惑?
最佳答案
Webpack 不支持将文字以外的参数传递给 require.context
。 reason github上项目负责人给出的是:
It must be statically analyzable...
理论上可以对此进行动态分析:
var testPath = '../src';
console.log("PATH 2 " + testPath); // ../src
var appContext = require.context(testPath, true, /\.spec\.ts/);
并发现require.context
的第一个参数是../src
。但是,当您遇到以下情况时,事情会变得更加复杂:
// If in browser use "foo", otherwise use "bar". (The test has been
// simplified as it is not our focus here.)
var testPath = (typeof window !== "undefined") ? "foo" : "bar";
var appContext = require.context(testPath, true, /\.spec\.ts/);
上面的代码无法被Webpack有意义地解析。是否在浏览器中是一个运行时条件,但 Webpack 是在构建时而不是运行时执行分析。启用动态分析除了会产生巨大成本之外,仍然不适用于许多用例场景。
关于webpack - 为什么我无法通过传递变量来确定 karma shim 中 require.context 的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45458809/