簡體   English   中英

Javascript 將 main.js 拆分為兩個文件(導入?需要?)

[英]Javascript split main.js into two files (import? require?)

我的超長文件 (main.js) 可以正常工作。 但我想將處理“y”的函數拆分為一個單獨的文件以進行組織。 在 PHP 中,我會使用 require('yfunctions.php') 並完成它。

javascript中是否有不需要重寫函數調用的等價物?

主.js:

// do stuff

function first(x){
  // do stuff with x
}

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}

最終變成:

主.js:

require('yfunctions.js');
// do stuff

function first(x){
  // do stuff with x
}

yfunctions.js:

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}

以上不起作用(似乎)。 我是否必須為 yfunctions.js 中的每個函數添加“導出”聲明? 有沒有辦法說“將此文件中的每個函數導出為函數?”

(注意,我正在使用 node.js / electron ......但我很好奇關於 javascript 如何工作的一般知識。)

使用module.exports導出模塊的成員。 在您的示例中:

module.exports.second = second;
module.exports.third = third;

function second(y){
  // do stuff to y
  // return y
}
    
function third(y){
  // do stuff with y
}

沒有選項可以自動導出模塊的所有成員。

如果你在 ES6 中工作,上面的內容可以簡化為:

module.exports = {
  second,
  third
};

function second(y){
  // do stuff to y
  // return y
}
    
function third(y){
  // do stuff with y
}

最后,在您的main.js中,您可以通過為require語句指定名稱來調用其他模塊的導出函數:

const yfunctions = require('./yfunctions');

yfunctions.second(y);

在這種情況下,您必須使用模塊導出,並使用 require 導出其他存檔中的功能。 在你可以使用之后,檢查我的例子

函數.js

module.exports = {
  foo: function () {
    // do something
  },
  bar: function () {
    // do something
  }
};

var tryit = function () {
}

使用 functions.js 中的函數

var callFunction = require('./functions');
console.log(typeof callFunction .foo); // => 'function'
console.log(typeof callFunction .bar); // => 'function'
console.log(typeof callFunction .tryit); // => undefined because does not use exports

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM