最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I get VsCode to auto import correctly from an es6 module? - Stack Overflow

programmeradmin2浏览0评论

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

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

How do I fix this?

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

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

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

How do I fix this?

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

Share Improve this question asked Jun 23, 2020 at 15:49 NeutrinoNeutrino 9,74510 gold badges66 silver badges99 bronze badges 2
  • Have you tried adding "esModuleInterop":true in pilerOptions? – isAif Commented Jun 23, 2020 at 16:30
  • Yes tried that too. It adds the same CommonJS style import. – Neutrino Commented Jun 23, 2020 at 18:00
Add a ment  | 

1 Answer 1

Reset to default 4

in most case , it will work fine with a jsconfig at root. ex: jsconfig.json

{
    "pilerOptions": {
        "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"],
    "pilerOptions": {
        "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.

发布评论

评论列表(0)

  1. 暂无评论