定位ECMAScript 6或更高版本时,不能使用带有'require'的导入 [英] Import with 'require' cannot be used when targeting ECMAScript 6 or higher

查看:25
本文介绍了定位ECMAScript 6或更高版本时,不能使用带有'require'的导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In VS2019 16.2.1, I created a new project using the Basic Azure Node.js Express 4 Application with TypeScript Template.

我可以构建并运行该应用程序.

I can build and run the application.

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

However, in app.ts, if I hover over the line

import debug = require('debug');

我看到一个工具提示

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

这是tsconfig.json

Here is tsconfig.json

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

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

Why do I see this message and what should I do about it?

[更新]

我尝试将第一行更改为

从调试"导入调试;

然后我得到构建错误

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时,警告消失.

[Update] The warning dissappears when I suspend Resharper Ultimate.

如果我切换到ES5并尝试

If I switch to ES5 and try

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

我看到一个错误

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

如果我使用

import * as debug from 'debug' 

有效

推荐答案

而不是使用

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中的新语法

(了解更多)

如果要使用旧版的导入模块,可以在 tsconfig.json 中将"target" 设置为"ES5" 文件.

If you want to use the old style of importing modules you can set "target" to "ES5" in your tsconfig.json file.

这篇关于定位ECMAScript 6或更高版本时,不能使用带有'require'的导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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