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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:34:01  来源:igfitidea点击:

How do I call .js from another .js file?

javascriptnode.js

提问by jeny

I have mysql connection code which I need to call each time in every .js file. Say I want sql.jsfrom main.js. I am thinking include(sql.js)?

我有 mysql 连接代码,每次都需要在每个 .js 文件中调用。说我想sql.jsmain.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
 }

};