Javascript 在客户端js中导入代码;在当前范围内的任何位置
假设我有两个文件front.js和other.js。我需要在front.js中添加来自other.js的代码Javascript 在客户端js中导入代码;在当前范围内的任何位置,javascript,module,scope,Javascript,Module,Scope,假设我有两个文件front.js和other.js。我需要在front.js中添加来自other.js的代码 front.js- // blah var obj= { a: function(){ // more blah }, b: function(){ // more blah }, /* get c: function(){ // more blah },
front.js-
// blah
var obj= {
a: function(){
// more blah
},
b: function(){
// more blah
},
/*
get
c: function(){
// more blah
},
here
*/
d: function(){
// more blah
}
};
// blah
其他.js-
c: function(){
// more blah
},
// this ^^ is all that there is in the file (invalid js)
如何在
front.js
的正确位置导入other.js
中的代码这不是客户端模块加载器(甚至是依赖于有效代码结构的一般模块系统)所能做的,而是构建脚本所能做的。它只需扫描文件中的
include
指令,并用引用文件的内容逐字替换它们。有关将文件连接在一起的简单示例,请参阅。谢谢@Bergi,您的提示方向正确
我最终是这样做的:
假设front.js是
// blah
var obj= {
a: function(){
// more blah
},
// other.js
c: function(){
// more blah
}
};
// blah
而other.js是-
b: function(){
// more blah
},
使用创建app.js
var bigstr= "", otherstr= "";
var count= 0;
var frontstream= fs.createReadStream("path/to/front.js");
frontstream.on("data", function(chunk){
bigstr+= chunk;
});
frontstream.on("error", function(error){
console.log("front error");
});
frontstream.on("end", function(){
var otherstream= fs.createReadStream("path/to/other.js");
otherstream.on("data", function(chunk){
otherstr+= chunk;
});
otherstream.on("error", function(){
console.log("other error");
});
otherstream.on("end", function(){
count+= 1;
check();
});
});
function check(){
if(count===1){
bigstr= bigstr.replace("// other.js", otherstr);
fs.writeFile("path/to/newfront.js", bigstr, function(err){
if(!err){
console.log("done");
}
});
}
}
c:46,
是无效的javascript,因此无法命名文件other.js
。一个选项是使other.js
成为导出值的模块,然后在front.js
中引用它。但是你似乎需要动态地组装js
代码,但是如果没有额外的细节,很难判断你在做什么。sc:46,是无效的js,是的,我知道。我正在看一个包含不同js文件(不一定是有效的js)的项目,如果将这些文件连接在一起,它们将是有效的js。想要调试它而不需要制作一个大的js文件或将不同的文件重构成适当的模块!