1

I'm working on a little 1 file function in Node.js.

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.

I've created a file with just the array.

my-array.js

const myArr = [//stuff];

And have tried many ways of including it in my main.js file, eg:

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

Or trying the ES6 way:

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

(adding export to my-array and changing file type to .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?

1
  • Are there any errors when you try to import with import/export? Commented Sep 12, 2022 at 7:00

2 Answers 2

1

for the first one:

module.exports = []; // your array
Sign up to request clarification or add additional context in comments.

Comments

1

You could either use the ES6 module import syntax

// 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.