使用 TypeScript 和 nodemon:SyntaxError:不能在模块外使用导入语句 [英] Using TypeScript and nodemon: SyntaxError: Cannot use import statement outside a module

查看:160
本文介绍了使用 TypeScript 和 nodemon:SyntaxError:不能在模块外使用导入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am converting the code to use nodemon to leverage 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

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

有没有办法继续使用这种import?

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

推荐答案

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

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

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

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

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

这篇关于使用 TypeScript 和 nodemon:SyntaxError:不能在模块外使用导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆