简体   繁体   中英

Can you use ES6 import/export in typicode json-server

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?

如果你的 Node 版本是 13.0.0 或更高,我认为你需要在 package.json 中添加"type": "module"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM