Why can't I determine the path for require.context in a karma shim by passing a variable?

一个人想着一个人 提交于 2021-02-10 17:27:34

问题


I want to set the path for require.context(path, ...) in a shim file called by karma (set in the files parameter in the config) dynamically, but somehow, as soon as I use a variable for path, I get the error 'Cannot find module "."' in the CLI. This is very odd, because if I hardcode the very same path into the call, it runs without a problem. Aka, if I do

var testPath = '../src';
console.log("PATH 2 " + testPath); // ../src
var appContext = require.context(testPath, true, /\.spec\.ts/);

I'll get an error, if I do

var appContext = require.context('../src', true, /\.spec\.ts/);

everything is fine.

In the full shim file the code appears exactly as I have written it here, aka there is no other code between the definition of testPath and require.context, I just included the console.log to check for some inexplicable voodoo.

The shim is invoked as follows in the 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);
};

What am I missing? Does the call to the same shim by preprocessors mess things up?


回答1:


Webpack does not support passing parameters other than literals to require.context. The reason given by the project owner on github is:

It must be statically analyzable...

It would be possible in theory to do a dynamic analysis of this:

var testPath = '../src';
console.log("PATH 2 " + testPath); // ../src
var appContext = require.context(testPath, true, /\.spec\.ts/);

and discover that the first parameter to require.context is ../src. However, it gets more complicated when you have things like:

// 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/);

The code above cannot be meaningfully resolved by Webpack. Whether or not you are in a browser is a run time condition but Webpack is performing its analysis at build time, not at run time. Enabling dynamic analysis, besides the significant cost it would have, would still not work for a lot of use-case scenarios.



来源:https://stackoverflow.com/questions/45458809/why-cant-i-determine-the-path-for-require-context-in-a-karma-shim-by-passing-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!