【问题标题】:Import with 'require' cannot be used when targeting ECMAScript 6 or higher以 ECMAScript 6 或更高版本为目标时,不能使用“require”导入
【发布时间】:2019-12-16 16:37:57
【问题描述】:

在 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

如果我使用

import * as debug from 'debug' 

有效

【问题讨论】:

    标签: typescript ecmascript-6 resharper


    【解决方案1】:

    听起来您想将这些导入更改为这种样式:

    import debug from 'debug';
    

    或在tsconfig.json 中将"target" 设置为"ES5""ES3"

    【讨论】:

    • 谢谢,我更新了我的问题,试图改变风格。
    • 链接 tsconfig.json 有效。 (或暂停 resharper )
    【解决方案2】:

    而不是使用

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

    (Read more)

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2020-04-28
    • 2020-07-31
    相关资源
    最近更新 更多