简体   繁体   English

如何在javascript中动态使用“ require”?

[英]How to use “require” dynamically in javascript?

I have a javascript function in "sample.js" file. 我在“ sample.js”文件中有一个javascript函数。 It is like this: 就像这样:

var mapDict = { '100': 'test_100.js', '200': 'test_200_API.js', '300': 'test_300_API.js' }

function mapAPI()
{
    this.version = 0.1;
}

mapAPI.prototype.getFileName = function( id ) {
   return mapDict[id]
}

module.exports = mapAPI;

in another file named "institute.js" I want to require the above "test_xxx_API" files dynamically. 在另一个名为“ institute.js”的文件中,我希望动态地需要上述“ test_xxx_API”文件。 I have the following code: 我有以下代码:

const mapAPI  = require('../../sample.js');
const map     = new mapAPI();
const mapFile = map.getFileName("100");
var insAPI    = require(mapFile);

When I run this code by "node institute.js" command, I get the following error: 当我通过“ node institute.js”命令运行此代码时,出现以下错误:

Error: Cannot find module './test_100_API.js'.

But the "test_100_API.js" file exists and is located in the current folder besides "institute.js". 但是,“ test_100_API.js”文件存在,并且位于“ institute.js”之外的当前文件夹中。 When I changed var insAPI = require(mapFile); 当我更改var insAPI = require(mapFile); to var insAPI = require("./test_100_API.js"); var insAPI = require("./test_100_API.js"); and give it the exact path instead of dynamic path, it works fine. 并为其指定确切的路径而不是动态路径,它可以正常工作。 Can anyone help me? 谁能帮我?

Thanks in advance 提前致谢

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

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