1

I have a test file with the following import at the top

import pizzas from '../data';

the data file here is data.json and contains an array of objects, this file has no export anywhere inside it so I was wondering how is the import working as I thought you'd need a matching export.

j obe
  • 1,759
  • 4
  • 15
  • 23
  • It's not supported natively in browsers, but it can work in Node and lots of build systems, which have coded extensions allowing for the direct importing of JSON – CertainPerformance Jan 05 '21 at 02:27
  • @CertainPerformance thanks - so you can import and name the JSON data, without needing to export it? I am running it on the terminal so does that mean the test file is running in node? I thought I would need to use the require syntax for that. – j obe Jan 05 '21 at 02:46
  • Probably because of https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_experimental_json_modules. Related: https://github.com/tc39/proposal-json-modules https://github.com/whatwg/html/issues/4315 – CertainPerformance Jan 05 '21 at 02:55
  • @CertainPerformance I'm using node 12.10.0, so I don't understand how it's working. Also just to confirm I understand correctly, you can import and name a JSON data file without needing to export it? - I'm reading the article that was linked to my post to find the answer there but haven't seen that yet. – j obe Jan 05 '21 at 02:58
  • You need to use the `experimental-modules` flag to run MJS files, right? Node docs say that `--experimental-json-modules` is required as well for plain JSON to be parsed like that, but it doesn't appear to be necessary, since the JSON gets imported properly without that. Does that mean *any* ESM script in Node supports importing JSON like that? The docs aren't up to date? Not sure what's going on. – CertainPerformance Jan 05 '21 at 03:09
  • Me neither, I was following a unit testing tutorial and the setup of the code provided is a json data file which is imported into a spec.js test file, I was confused by the process of importing without an export and not needing require. Thanks for your help – j obe Jan 05 '21 at 03:20

0 Answers0