首页 > 解决方案 > 以 ECMAScript 6 或更高版本为目标时,不能使用“require”导入

问题描述

在 VS2019 16.2.1 中,我使用带有 TypeScript 模板的 Basic Azure Node.js Express 4 Application 创建了一个新项目。

模板选择

我可以构建和运行应用程序。

但是,在 app.ts 中,如果我将鼠标悬停在这条线上

import debug = require('debug');

我看到一个工具提示

Import with 'require' cannot be used when targeting ECMAScript 6 or higher

警告信息

这是 tsconfig.json

  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "lib": ["es6"],
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

为什么我会看到此消息,我应该怎么做?

[更新]

我尝试将第一行更改为

从“调试”导入调试;

然后我得到构建错误

app.ts(1,8): error TS1259: Module '"C:/Users/kirst/source/repos/ExpressApp1/ExpressApp1/node_modules/@types/debug/index"' can only be default-imported using the 'esModuleInterop' flag

[更新] 当我暂停 Resharper Ultimate 时警告消失。

如果我切换到 ES5 并尝试

import from 'debug'  ( with or without a semicolon )

我看到一个错误

can only be default-imported using the 'esModuleInterop' flag

esMOdule 互操作标志

如果我使用

import * as debug from 'debug' 

有用

标签: typescriptecmascript-6resharper

解决方案


而不是使用

import debug = require('debug');

你应该使用

import * as debug from 'debug' // Import everything from that module
// OR
import debug from 'debug' // Import only the class 'debug' from that module

// Depends on the module

这是 ES6 中的新语法

(阅读更多)

如果您想使用旧样式的导入模块,您可以在文件中设置"target"为。"ES5"tsconfig.json


推荐阅读