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
对于英语,你应该找到它,它可能需要时间。关于javascript - 如何让 VsCode 从 es6 模块正确自动导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62538738/