模块只能使用 esModuleInterop 标志默认导入

6,232 阅读2分钟

--- theme: github highlight: atom-one-dark ---

Module '"path"' can only be default-imported using the 'allowSyntheticDefaultImports' flagts(1259)

在vite.config.ts

2 分钟

阅读

照片由

[

Oksana Kurochkina 拍摄

](unsplash.com/photos/L_0x…)

[

](unsplash.com/photos/L_0x…)

模块只能使用 esModuleInterop 标志默认导入#

当我们尝试将 CommonJS 模块导入 ES6 模块时,会出现错误“Module can only be default-imported using esModuleInterop flag”。

要解决该错误,请将

**esModuleInterop

选项设置为

true

在您的

tsconfig.json

文件中。

**

模块只能默认导入

这是错误发生方式的示例。

索引.ts

// ⛔️ Error: Module '"path"' can only be
// default-imported using the 'esModuleInterop' flag ts(1259)
// This module is declared with using 'export =', and
// can only be used with a default import when
// using the 'esModuleInterop' flag.
import path from 'path';

console.log(path.join(__dirname, './another-file.ts'));

export const num = 42;

这里的问题是 -

path

是一个使用

exports

and

require

语法的 CommonJS 模块,我们正在尝试

使用默认导入将其导入

[

ES6 模块。

](www.typescriptlang.org/docs/handbo…)

要解决该错误,请将

esModuleInterop

选项设置为

true

在您的

tsconfig.json

文件中。

tsconfig.json

{
  "compilerOptions": {
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    // ... rest
  }
}

现在我们的导入按预期工作:

索引.ts

import path from 'path';

export const num = 42;

// ✅ "/home/borislav/Desktop/typescript/src/another-file.ts"
console.log(path.join(__dirname, './another-file.ts'));

如果这不能为您解决问题,请尝试重新启动 IDE 和服务器。

esModuleInterop

选项默认设置为

[

](www.typescriptlang.org/tsconfig#es…)

false

这使其将 CommonJS 模块视为类似于 ES6 模块。

这会导致一些问题。

设置

esModuleInterop

true

解决这些问题。

esModuleInterop

设置使用两个辅助函数更改编译器的行为,这两个辅助函数提供了一个 shim 以使发出的 JavaScript 兼容。

当您设置

esModuleInterop

为 时

true

,您还启用了

[

allowSyntheticDefaultImports

](www.typescriptlang.org/tsconfig#al…)

选项。

启用后,

当模块未明确指定默认导出时,

allowSyntheticDefaultImports

允许我们在不使用星号的情况下编写导入。

*

索引.ts

import React from 'react';

import path from 'path';

import fs from 'fs';

代替:

索引.ts

import * as React from 'react';

import * as path from 'path';

import * as fs from 'fs';

例如,该

path

模块不提供默认导出,因此如果我们尝试使用

allowSyntheticDefaultImports

set to导入它

false

,我们会收到错误消息。

索引.ts

// ⛔️ Error: Module '"path"' can only be
// default-imported using the 'esModuleInterop' flag ts(1259)
import path from 'path';

错误的原因是 - 没有

default

我们可以从模块导入的对象。

如果这不能为您解决问题,请尝试重新启动 IDE 和服务器。

另一种方法是使用

import * as x

语法。

索引.ts

import * as path from 'path';

export const num = 42;

// ✅ "/home/borislav/Desktop/typescript/src/another-file.ts"
console.log(path.join(__dirname, './another-file.ts'));

请注意,诸如此类的导入

import * as x

仅考虑拥有的属性(不通过原型链继承)。

如果导入使用继承属性的模块,则必须使用默认导入语法 -

import path from 'path'