首页 > 解决方案 > 如何使用“require”而不是“import”语句

问题描述

在 JavaScript、node.js 中,当我使用 CommonJS 样式导出模块时,例如

module.export.foo = (param) => {
    // do sth here
   return value
}

然后我开始foo在我的 node.js 项目中输入另一个文件,VS Code 建议:“从 'path/to/file' 自动导入”按回车后,VS Code 在文件顶部插入语句:

import { foo } from 'path/to/file'

我希望 VS 代码改为粘贴以下代码:

const { foo } = require('path/to/file')

可能吗?

我的jsconfig.json样子是这样的:

{
    "compilerOptions": {
      "module": "commonjs",
      "target": "es6"
    },
    "include": [
        "src/**/*",
        "__tests__/**/*"
    ]
  }

标签: node.jsvisual-studio-codenode-modules

解决方案


在 v1.46 中,这应该会更好:

CommonJS 自动导入

如果 VS Code 检测到您正在使用 CommonJS 样式的 JavaScript 模块,自动导入现在将使用require而不是import.

v1.46 发布说明:CommonJS 导入


推荐阅读