使用TypeScript和nodemon:SyntaxError:无法在模块外部使用import语句

问题描述 投票:0回答:1

我正在转换代码以使用nodemon来利用TypeScript。

在我的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"
  },

fake-api/server.ts文件:

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')
});

但是运行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

我在Google上搜索了一下并在这里结束:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

是否有变通办法可以继续使用这种import

node.js typescript nodemon
1个回答
0
投票

我在相关的GitHub问题线程上回答了我的问题:https://github.com/remy/nodemon/issues/1625#issuecomment-560115741

我通过在commonjs而不是tsconfig.json中用esnext更改模块类型解决了我的问题,

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
...
© www.soinside.com 2019 - 2024. All rights reserved.