如何从另一个.js文件调用.js

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

本文关键字:js 文件 调用 另一个      更新时间:2023-09-26

我有mysql连接代码,每次都需要在每个.js文件中调用它。说我想从main.js那里得到sql.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");
}

您可以创建一个模块,并通过以下方式要求它。

文件 A:sql.js

var a = function a(){
};
module.exports.a = a;

文件 B、C、D:

var sql = require("./sql");
sql.a();

require .

例如var sql = require('sql.js');

你需要在 sql.js 中返回一个带有 module.exports = myobj 的对象;

例:

module.exports = {
 sql_connection: null,
 connect: function() {
    // connect to db
   this.sql_connection = ... ; // code to connect to the db
 }
};