简体   繁体   English

node.js / browserify require()不适用于变量,但确实适用于字符串文字

[英]node.js/browserify require() not working on variable, but does work on string literal

    const x = 'ui/SelectBox.js';
    const module = require(x);

does not work (Error: Cannot find module 'ui/SelectBox.js'), but somehow 不起作用(错误:找不到模块'ui / SelectBox.js'),但是以某种方式

    const module = require('ui/SelectBox.js');

works. 作品。 Also, if I call node on the commandline and do 另外,如果我在命令行上调用node并执行

var x = 'ui/SelectBox.js'; require(x); 

it does work. 它确实有效。

I'm doing it on a win10 machine, but also tested the same thing under debian and got the same result. 我在win10机器上进行此操作,但也在debian下测试了相同的东西,并获得了相同的结果。 Oh, and I'm using watchify (tried it with browserify itself, to the same results...). 哦,我正在使用watchify(将其与browserify一起尝试,以得到相同的结果...)。

node --version

-> v5.6.0 -> v5.6.0

EDiT: Okay, read my own answer. EDiT:好的,请阅读我自己的答案。 It might save you some trouble. 它可以为您省去一些麻烦。

The answer to the riddle is, as always, depressingly simple. 与往常一样,谜语的答案非常简单。

You cannot abstract your require()s if you use browserify, because (I guess) browserify parses your source for requires. 如果使用browserify,则不能抽象您的require(),因为(我想)browserify会解析源中的需求。

So if you absolutely have to require() over a variable, make an object that maps names to require()d modules, and then use that. 因此,如果绝对必须在变量上使用require(),请创建一个将名称映射到require()d模块的对象,然后使用该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM