1
//level1.js

[[1,2,3,0,0],
[0,0,0,4,0],
[0,4,2,0,0],
[0,0,0,0,0],
[0,0,1,3,0]];

I'm making a game and I want this array of arrays to be imported into my game.js file. (To be able to choose the map)

//game.js

let map = "level1"

import * as gameBoard from `./${map}.js`



2
  • You are not exporting anything from level1.js. And I think that you can't use template strings for import statements. Commented Oct 27, 2019 at 15:36
  • @VLAZ so how should I do? Commented Oct 27, 2019 at 15:37

2 Answers 2

8

You need to export your array in level1.js.

  //level1.js

  export const array = [
    [1,2,3,0,0],
    [0,0,0,4,0],
    [0,4,2,0,0],
    [0,0,0,0,0],
    [0,0,1,3,0]
  ];

And then you can import the variable from game.js

//game.js
import { array } from './level1.js'
Sign up to request clarification or add additional context in comments.

2 Comments

It says "Cannot use import statement outside a module" :/
You need to use ES6 for the solution above. Otherwise you have to use module exports
0

if you're running your scripts using "node script.js",then you're gonna have to use the "exports/require" method:

  • In level1.js:

exports.array = [1, 2, 3];

  • In game.js:

const level1 = require('./level1');
    
// then access it like so
console.log(level1.array);

If, however, you wanted to use the "import" syntax that the guys are suggesting above, then you're gonna have to enable ES6 syntax.

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.