0

I want to use import in my file, but I cant find the way to replace my require properly

See the code I want to replace

const object = {
  first: require('../example/first.json').EXL.PUBLIC,
  second: require('../example/second.json').EXL.PUBLIC,
  third: require('../example/third.json').EXL.PUBLIC
}

First question is how can I import those stuff directly to an object? Just like I did with require?

The second one, how can I use import with the .EXL.PUBLIC command? To directly import the right branch of the json file?

2
  • 1
    What environment are you doing this in? Node.js? What version? Commented Apr 10, 2019 at 9:32
  • 1
    assuming nodejs ... read the friendly documentation Commented Apr 10, 2019 at 9:33

1 Answer 1

1

First question is how can I import those stuff directly to an object?

You can't, you have to import them and then add them to the objct.

The second one, how can I use import with the '.EXL.PUBLIC' command?

You have to import the item, then extract that property.

I'm going to assume you're using Node.js:

v8 through v11

In an .mjs module, you can do it like this:

import firstRoot from "../example/first.json";
import secondRoot from "../example/second.json";
import thirdRoot from "../example/third.json";

const object = {
  first: firstRoot.EXL.PUBLIC,
  second: secondRoot.EXL.PUBLIC,
  third: thirdRoot.EXL.PUBLIC
};

v12

You can still do it as in v11.

If you use ESM with a .js file via the new "type": "module" in package.json, you need to add the --experimental-json-modules flag to enable JSON loading. More about v12's support here, but note that --type isn't yet supported (and if it is, will probably be --entry-type), and the JSON flag is --experimental-json-modules, not --experimental-json-loader).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.