webpack - 为什么我无法通过传递变量来确定 karma shim 中 require.context 的路径?

标签 webpack karma-runner require

我想在 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.contextreason 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/

相关文章:

javascript - RequireJS require() 无法解析同一子目录级别的文件名

ruby - Rake 任务不会在我的 sinatra 应用程序中运行

javascript - webpack 无法解析 bootstrap-loader 的 bootstrap 模块

unit-testing - Angular 返回模块中的测试服务未定义

javascript - 安装后如何运行 Karma?

angularjs - 如何模拟 $window 来单元测试 AngularJS 服务?

ruby - 如果 'require sinatra' 在另一个文件中,为什么 sinatra 不会加载?

javascript - 无法在带有 webpack/rollup/react 的外部库中使用 Material UI

webpack - 如何设置 "Content Encoding"为 Webpack 服务器启用 gzip 文件

https - 如何使用 https 运行 Vue.js 开发服务?