![](/img/trans.png)
[英]JavaScript export array from one file to another to be used. Node.js
[英]JS - Export array from one file to another
所以,我在 .js 文件中有以下數組:
//file name: myVar.js
var myVar= [
{id:1, items:
[
{
"Name": "John",
"Surname": "Doe",
"Country": "Portugal"
}
]},
{id:2, items:
[
{
"Name": "Mary",
"Surname": "Jane",
"Country": "France"
}
]
}
]
我想要做的是,在另一個 .js 文件中調用它,例如:
//file name: expVar.js
var expVar = //var exported
我已經嘗試了一些我通過互聯網發現的東西,但似乎都沒有奏效。 先謝謝您的幫助。
只需使用 export 關鍵字
export var expVar
並在其他文件中導入 expVar
許多現代瀏覽器都支持JavaScript 模塊,您可以使用它從一個文件中export
數組並將其import
到另一個文件中。
它看起來像這樣:
// myVar.js
export var myVar = [/* your content */];
在你的第二個文件中:
// expVar.js
import { myVar } from './myVar.js'
// Now you can use `myVar` here directly!
console.log(myVar);
PS:很多時候,你會有某種打包器(例如Webpack或Parcel )為你組裝不同的 JavaScript 文件。 它們可能支持不同類型的模塊(例如require
),但 JavaScript 模塊是最常見的模塊之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.