如何让 VsCode 从 es6 模块正确自动导入?

Neu*_*ino 5 javascript visual-studio-code es6-modules

lib1.js 是一个 es6 模块

export function greet() {
   console.log('Hello from Greet');
}
Run Code Online (Sandbox Code Playgroud)

在 main.js 中调用greet(). VsCode 自动导入将为

const { greet } = require('./lib1');
Run Code Online (Sandbox Code Playgroud)

...代替

import { greet } from './lib1';
Run Code Online (Sandbox Code Playgroud)

jsconfig.json

{
   "compilerOptions": {
      "target": "es6",
      "allowSyntheticDefaultImports": true
   },
   "module": "es2015"
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

PS 我"type": "module"也在 package.json 中尝试过。

jon*_*jon 3

在大多数情况下,它可以在 root 下正常工作jsconfig。例如:jsconfig.json

{
    "compilerOptions": {
        "target": "es2020",
        "module": "esnext",
        "jsx": "react",
        "checkJs": true,
        "lib": ["esnext", "dom"],
        "esModuleInterop": true, // force import
        "moduleResolution": "node",

        "allowSyntheticDefaultImports": true, // force import
    },
    "include": ["src/**/*"]
}

Run Code Online (Sandbox Code Playgroud)

但如果出于某种原因您还在根目录中使用 a tsConfig(例如从 js 生成 d.ts ),您将需要添加"allowJs": true ex: tsConfig.json

{
    "include": ["src/"],
    "exclude": ["node_modules"],
    "compilerOptions": {
        "target": "ES6",
        "module": "ES6",
        "jsx": "react",
        "esModuleInterop": true,
        "checkJs": true,
// default false, and will break jsconfig import, because with ts, vscode will think all js file are for nodejs, and no sugar import for nodejs.
        "allowJs": true,

        "lib": ["esnext", "dom"],
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "allowUnreachableCode": true,
        "outDir": "types/",
        "emitDeclarationOnly": true,
        "declaration": true
    }
}
Run Code Online (Sandbox Code Playgroud)

完成所有编辑后,您应该重新启动 ts 服务器。输入restart英语,您应该可以找到它,但这可能需要一些时间。 在此输入图像描述