0

I'm using https://github.com/typicode/json-server to stand up a mock API. I'm using a .js file to programmatically generate the data. I would like to use the import/export default syntax to import and export javascript, but I can't get it to build.

I would like to use:

import data from './data';

export default () => {
  return {data: data};
};

But the only way I can get it to work is using this syntax:

const data = require('./data');

module.exports = () => {
  return {data: data};
};

This is sitting in a file called db.js, and I run the mock API using json-server --watch db.js. The same issue applies to the data.js file. Here is the error I get when trying to run it:

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
...

I have tried moving this to different subdirectories with no success. Is there anything I can do to allow this app to run with the import/export default syntax?

matt h
  • 1
  • 1
  • Welcome to StackOverflow! Can/did you check if the answers in this post help you? https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node – saglamcem Feb 13 '20 at 15:47
  • None of those answers worked for me. I believe it's because those answers use ```node``` to run the app and I am using ```json-server```. – matt h Feb 13 '20 at 16:35
  • You're writing standard node JS so you can use whatever ECMAScript syntax your particular node version (and V8 engine) supports, which might surprise you it will have most the new constructs you are used to using short of import statements. If you must use import/export, you'd need to setup babel to transpile your modern ES to node friendly-ES to get it to work. – user210757 Mar 05 '20 at 22:30
  • json-server is a node application and library – user210757 Mar 05 '20 at 22:36

1 Answers1

0

I think you need to add "type": "module" in the package.json if your Node version is 13.0.0 or more.

Marsou001
  • 11
  • 2