Using TypeScript and nodemon: SyntaxError: Cannot use import statement outside a module

十年热恋 提交于 2020-03-05 03:14:22

问题


I am converting the code to use nodemon to leverage TypeScript.

In my package.json:

  "scripts": {
    "serve-fake-api": "nodemon fake-api/server.ts --watch 'fake-api/*.*'  ",
    "serve-vue": "vue-cli-service serve",
    "serve": "concurrently -k \"npm run serve-fake-api\" \"npm run serve-vue\"",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },

and the fake-api/server.ts file:

import { readFileSync } from 'fs';
import { create, defaults, bodyParser, rewriter, router as _router } from 'json-server';
import { join } from 'path';

const server = create();
const defaultMiddleware = defaults();

// It is recommended to use the bodyParser middleware before any other middleware in your application
server.use(bodyParser);

server.use(defaultMiddleware);

// Define custom routes (routes.json)
const routes = JSON.parse(readFileSync(join(__dirname, 'routes.json'), "utf8"));
server.use(rewriter(routes));

// Add custom middleware before JSON Server router
const customMiddleware = require(join(__dirname, 'middleware.ts'));
server.use(customMiddleware);

// This is where `json-server`'s magic happens ;)
const router = _router(join(__dirname, 'db.json'));

// Start the application by listening to port 3000,
// Although this won't print the nice starting message you see when
// running `json-server` as CLI command, it still runs the app correctly.
server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running')
});

but when running npm run serve:

[0] C:\Users\eperret\Desktop\tabulator-tests\fake-api\server.ts:1
[0] import { readFileSync } from 'fs';
[0] ^^^^^^
[0]
[0] SyntaxError: Cannot use import statement outside a module

I googled a bit and ended up here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Is there a workaround to keep using this kind of import?


回答1:


I answered to my question on the related GitHub issue thread: https://github.com/remy/nodemon/issues/1625#issuecomment-560115741

I solved my issue by changing the module type with commonjs in tsconfig.json instead of esnext:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
...


来源:https://stackoverflow.com/questions/58778055/using-typescript-and-nodemon-syntaxerror-cannot-use-import-statement-outside-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!