Javascript 如何从另一个 .js 文件调用 .js?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36048938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I call .js from another .js file?
提问by jeny
I have mysql connection code which I need to call each time in every .js file. Say I want sql.js
from main.js
. I am thinking include(sql.js)
?
我有 mysql 连接代码,每次都需要在每个 .js 文件中调用。说我想sql.js
从main.js
。我在想include(sql.js)
?
sql.js
var sql = require('sql');
var connection = sql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'db'
});
connection.connect(function(err){
if(!err) {
console.log("connected");
}
回答by Pavel
You can create a module, and require it the following way.
您可以创建一个模块,并按以下方式要求它。
File A: sql.js
文件 A:sql.js
var a = function a(){
};
module.exports.a = a;
Files B, C, D:
文件 B、C、D:
var sql = require("./sql");
sql.a();
回答by Pierre Emmanuel Lallemant
require
.
require
.
for example var sql = require('sql.js');
例如 var sql = require('sql.js');
you need in the sql.js to return an object at the end with module.exports = myobj
;
你需要在 sql.js 最后返回一个对象module.exports = myobj
;
Example:
例子:
module.exports = {
sql_connection: null,
connect: function() {
// connect to db
this.sql_connection = ... ; // code to connect to the db
}
};