Neutrino
Neutrino

Reputation: 9594

How do I get VsCode to auto import correctly from an es6 module?

lib1.js is an es6 module

export function greet() {
   console.log('Hello from Greet');
}

In main.js call greet(). VsCode auto import will add an import for

const { greet } = require('./lib1');

...instead of

import { greet } from './lib1';

jsconfig.json

{
   "compilerOptions": {
      "target": "es6",
      "allowSyntheticDefaultImports": true
   },
   "module": "es2015"
}

How do I fix this?

P.S. I've tried "type": "module" in package.json too.

Upvotes: 5

Views: 5406

Answers (1)

jon
jon

Reputation: 1808

in most case , it will work fine with a jsconfig at root. ex: 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/**/*"]
}

but if for any reason you use also a tsConfig in your root (example for generate d.ts from js), you will need to add "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
    }
}

After all edit, you should restart ts server. type restart for English, you should found it and it can take time. enter image description here

Upvotes: 4

Related Questions