我具有一段相同的代码结构,并希望访问其他文件中定义的功能...我该怎么做parent()
module.exports & require
app.js
var x= require('./invkFunc1');
x.display1();
x.display2();
x.display3();
invkFunc1.js
var x = require('./invkFunc2');
(function(x){
//var x= {}
disp1 = "hello i am from display1"
x.display1 = function(){
console.log(disp1)
}
return x;
}(x));
invkFunc2.js
var x = require('./invkFunc3');
(function(x){
//var x= {}
x.disp2 = "hello i am from display2"
x.display2 = function(){
console.log(x.disp2)
}
return x;
}(x));
invkFunc3.js
module.exports =
(function(){
var x= {}
x.disp3 = "hello i am from display3";
x.display3 = function(){
console.log(x.disp3)
}
return x;
}());
error:
我要从所有这些示例中看到,我如何访问较低级别的文件并使这些文件中定义的功能对某些存在的所有文件可用。
这样做是为了使我能够像以前一样通过将这些代码放在一个文件中来实现完美的模块化。
x.display1();
^
TypeError: x.display1 is not a function
at Object.<anonymous> (c:\Users\prabhat.mishra\Desktop\Chrome-DOM-EXT\extension as on 2rd july 2018\SampleExtension\module.exports\app.js:39:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
:Working code:
trying to achieve modularization from above code of below code
谢谢!
答案 0 :(得分:1)
如果要使用“ require”,则应先导出,然后可以这样编码
app.js:
"fzaninotto/faker": "^1.8",
"phpunit/phpunit": "^7.2@stable",
"codeception/codeception": "^2.4",
"jonnyw/php-phantomjs": "4.*",
"lucatume/wp-browser": "~1.21",
"codeception/phpunit-wrapper": "^7.1"
invkFunc1.js
var x = require('./invkFunc1');
x.display1();
x.display2();
x.display3();
invkFunc2.js
var x = require('./invkFunc2');
var disp1 = "hello i am from display1"
x.display1 = function(){
console.log(disp1)
}
module.exports = x;
invkFunc3.js
var x = require('./invkFunc3');
var disp2 = "hello i am from display2"
x.display2 = function(){
console.log(disp1)
}
module.exports = x;