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

折月煮酒 提交于 2021-02-08 08:52:06

问题


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.

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

import debug = require('debug');

I see a tooltip

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

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?

[Update]

I tried changing the first line to

import debug from 'debug';

then I get build errors

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

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

If I switch to ES5 and try

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

I see an error

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

If I use

import * as debug from 'debug' 

It works


回答1:


Instead of using

import debug = require('debug');

you should use

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

This is the new Syntax in ES6

(Read more)

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




回答2:


Sounds like you want to change those imports to this style:

import debug from 'debug';

Or in tsconfig.json set "target" to "ES5" or "ES3".



来源:https://stackoverflow.com/questions/57421543/import-with-require-cannot-be-used-when-targeting-ecmascript-6-or-higher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!