简体   繁体   English

如何将 a.js 文件中的数组包含到 another.js 文件中?

[英]How to include array from a .js file into another .js file?

I'm working on a little 1 file function in Node.js.我正在处理 Node.js 中的一个小文件 function。

This function uses an (normal vanilla js) array of data that is becoming very large and I'd like to move it to its own file to keep things tidy.这个 function 使用一个(普通的 vanilla js)数据数组,该数组变得非常大,我想将它移动到自己的文件中以保持整洁。

I've created a file with just the array.我创建了一个仅包含数组的文件。

my-array.js我的数组.js

const myArr = [//stuff];

And have tried many ways of including it in my main.js file, eg:并尝试了多种方法将其包含在我的 main.js 文件中,例如:

const myArr = require('./my-array.js')

Or trying the ES6 way:或者尝试 ES6 方式:

import {myArr} from "./my-array.mjs";

(adding export to my-array and changing file type to.mjs) (将export添加到 my-array 并将文件类型更改为.mjs)

However, nothing seems to work and I cannot seem to find any clear information about how to achieve this.但是,似乎没有任何效果,我似乎找不到任何关于如何实现这一目标的明确信息。

Could anyone point me in the right direction?谁能指出我正确的方向?

for the first one:对于第一个:

module.exports = []; // your array

You could either use the ES6 module import syntax您可以使用 ES6 模块导入语法

// my-array.mjs
const myArr = []

export { myArr }

// main.mjs
import { myArr } from './my-array.mjs'

or use good old require或使用良好的旧要求

// my-array.js
const myArr = []

module.exports = { myArr }

// main.js
const { myArr } = require('./my-array.js')

In any case, make sure to export your array and for ESM, you need to use .mjs as a file extension在任何情况下,请确保导出您的数组,对于 ESM,您需要使用.mjs作为文件扩展名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM