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

标签 javascript visual-studio-code es6-modules

lib1.js 是一个 es6 模块

export function greet() {
   console.log('Hello from Greet');
}
在 main.js 中调用 greet() . VsCode 自动导入将为
const { greet } = require('./lib1');
...代替
import { greet } from './lib1';
jsconfig.json
{
   "compilerOptions": {
      "target": "es6",
      "allowSyntheticDefaultImports": true
   },
   "module": "es2015"
}
我该如何解决?
附言我试过"type": "module"在 package.json 中。

最佳答案

在大多数情况下,它可以与 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/**/*"]
}

但如果出于任何原因您还使用 tsConfig在您的根目录中(例如从 js 生成 d.ts),您需要添加 "allowJs": true例如: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
    }
}
完成所有编辑后,您应该重新启动 ts 服务器。
类型 restart对于英语,你应该找到它,它可能需要时间。
enter image description here

关于javascript - 如何让 VsCode 从 es6 模块正确自动导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62538738/

相关文章:

javascript - 如何在 WebGL 的裁剪空间坐标中找到当前输出像素位置?

javascript - 当 Router.route(uri, {name : templateName })

javascript - 如何使 TypeScript 输出有效的 ES6 模块导入语句?

javascript - Node JS : Route. get() 需要一个回调函数,但在使用 ES6 模块时得到了一个 [对象未定义]

javascript - 为什么 Document.prototype.getElementsByName 存在于 Chrome 中?

javascript - Eslint - 超出最大调用堆栈大小

javascript - 是否可以将 VS Code 代码完成配置为接受标点符号建议?

java - 从带有 Maven 的 Visual Studio Code for Java 开始

javascript - 跨团队共享 gitignored 文件

javascript - 默认导出类的新实例