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

2024-01-29

我正在转换代码以使用 nodemon 来利用 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')
});

但跑步时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

我用谷歌搜索了一下,最终来到这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

有没有解决方法可以继续使用这种import?


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

我通过更改模块类型解决了我的问题commonjs in tsconfig.json代替esnext:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 TypeScript 和 nodemon:语法错误:无法在模块外部使用 import 语句 的相关文章

随机推荐