打字稿:无法在模块外使用import语句 [英] Typescript: Cannot use import statement outside a module

查看:89
本文介绍了打字稿:无法在模块外使用import语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node js(07.10.19的最新版本的node.js)应用程序中有一个.ts文件,其中包含导入节点模块而没有默认导出的情况.我使用以下结构: import'Class'from'abc'; 当我运行代码时,出现以下错误:不能在模块外使用import语句.

I have a .ts file in node js (latest version of node.js for 07.10.19) app with importing node-module without default export. I use this construction: import { Class } from 'abc'; When i run the code, i have this error: Cannot use import statement outside a module.

在网络上,我看到了针对此问题的许多解决方案(针对.js),但这对我没有帮助,也许是因为我有打字稿文件.这是我的代码:

In the network i see many solutions for this problem (for .js), but it not helps to me, maybe because i have typescript file. Here's my code:

import { Class } from 'abc';
module.exports = { ...
    execute(a : Class ,args : Array<string>){ ...

这是我的tsconfig.json:

Here's my tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",

    "strict": true
  }
}

推荐答案

会告诉Node您正在使用ES2015模块,该模块应消除该错误,但是您需要通过在tsconfig.json中设置"module":"es2015" 而不是"commonjs" 来告诉Typescript生成这种类型的模块.

Adding "type": "module" to package.json will tell Node you are using ES2015 modules, which should get rid of the error, but then you will need to tell Typescript to generate this type of module by setting "module": "es2015" instead of "commonjs" in tsconfig.json.

但这会导致当前代码出现问题,因为尽管您使用的是ES6 import {} 语句,但是您使用的是commonJS module.exports = {} 语法进行导出,而Node的ES模块加载器将出现问题.有两种处理方法:

This however causes a problem with the current code because although you are using an ES6 import {} statement you are exporting using the commonJS module.exports = {} syntax, and Node’s ES module loader will have an issue with it. There are two ways to deal with it:

  1. 保留 module.exports ,但通过
  1. Keep the module.exports but tell Node to interpret this file as commonJS by giving it a .cjs extension.
  2. Change the export statement to ES2015 syntax: export function execute(…)..

第一个选项可能会有些棘手,因为编译器将输出.js文件,您必须一直将其更改为.cjs(据我所知).使用第二个选项,您应该能够使用Node运行文件(包括版本低于13.8的--experimental-modules标志).

The first option could get a bit tricky because the compiler will output .js files and you’d have to change it to .cjs all the time (as far as I know). With the second option you should be able to run the file with Node (including the --experimental-modules flag for versions < 13.8).

如果您绝对需要使用commonJS,也许最好为Node安装类型定义: @ types/node 并将导入更改为commonJS格式: require('abc')并保持其余设置不变(尽管您可以添加"type":"commonjs"到package.json来明确表示.)

If you absolutely need to use commonJS, perhaps it is better to install the type definitions for Node: @types/node and change the import to commonJS format: require('abc') and keep the rest of the settings as they are (though you can add "type": "commonjs" to package.json to be explicit).

这篇关于打字稿:无法在模块外使用import语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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