【问题标题】:Using TypeScript and nodemon: SyntaxError: Cannot use import statement outside a module使用 TypeScript 和 nodemon:SyntaxError:无法在模块外使用 import 语句
【发布时间】:2020-03-05 18:21:28
【问题描述】:

我正在转换代码以使用 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

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

是否有解决方法可以继续使用这种import

【问题讨论】:

  • 我认为您需要告诉 nodemon 在重新加载之前将文件编译为 JS,如下所述:stackoverflow.com/a/37979548/554021。我也想知道你为什么使用 TS 但你的 server.ts 文件看起来就像普通的 javascript
  • @Baruch 这是 JS 版本的 WIP。
  • @Baruch 如何在不全局安装的情况下使用ts-code
  • @Baruch 实际上我检查过,它已经在使用 ts-node...
  • 找出原因,将发布我的答案

标签: node.js typescript nodemon


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2021-03-10
    • 1970-01-01
    • 2021-04-01
    • 2020-06-29
    • 2021-04-22
    相关资源
    最近更新 更多