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?
CodePudding user response:
for the first one:
module.exports = []; // your array
CodePudding user response:
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