尝试导入错误“X”未从中导出

尝试导入错误“X”未从#导出

Attempted import error ‘X’ is not exported from

当我们尝试导入指定文件中不存在的命名导入时,会出现 React.js“尝试导入错误‘X’未导出自”。要解决该错误,请确保模块具有命名导出并且您没有混淆命名导出和默认导出和导入。

未从导出的尝试导入错误

下面是错误如何发生的示例。这是一个导出函数的文件。

另一个文件.js
// 👇️ Note: default export export default function sum(a, b) { return a + b; }

这是index.js我们导入函数的文件。

索引.js
// ⛔️ Attempted import error: 'sum' is // not exported from './another-file'. // 👇️ Note: using named import import {sum} from './another-file'; console.log(sum(5, 10));

请注意,another-file.js我们使用了默认导出,而在index.js
文件中我们使用了命名导入。
这就是发生错误的原因。

要解决错误“Attempted import error ‘X’ is not exported from”,请确保:

  1. 在导入时将命名的导出包在花括号中
  2. default将值导出为默认导出时使用关键字
  3. 每个模块最多只有 1 个默认导出,但可以有多个命名导出

以下是如何使用命名导出解决错误的示例。

另一个文件.js
// 👇️ Using named export export function sum(a, b) { return a + b; }

并导入index.js文件中的函数。

索引.js
// 👇️ Using named import import {sum} from './another-file'; console.log(sum(5, 10));

请注意,我们没有将default关键字用于命名导出,而是将命名导入用花括号括起来。

每个文件可以有多个命名导出,但只能有一个默认导出。

Here is an example of how to solve the error using default export and import.

another-file.js
// 👇️ default export export default function sum(a, b) { return a + b; }

And now we use a default import in the index.js file.

index.js
// 👇️ default import import sum from './another-file'; console.log(sum(5, 10));

Notice that we do not use curly braces when working with default imports.

You can have a maximum of 1 default export per file.

If you are exporting a variable as a default export, you have to declare it on 1
line and export it on the next. You can’t declare and default export a variable
on the same line.

index.js
// 👇️ default export const example = 'hello world'; export default example;

You can also mix and match, here’s an example.

another-file.js
// 👇️ default export export default function sum(a, b) { return a + b; } // 👇️ named export export const num = 15;

And here are the imports.

index.js
// 👇️ default and named imports import sum, {num} from './another-file'; console.log(sum(num, 10));

We used a default import to import the sum function and a named import to
import the num variable.

To solve the “Attempted import error ‘X’ is not exported from” error, be
consistent with your ES6 imports and exports. If a value is exported as a
default export, it has to be imported as a default import and if it’s exported
as a named export, it has to be imported as a named import.

Conclusion #

The React.js “Attempted import error ‘X’ is not exported from” occurs when we
try to import a named import that is not present in the specified file. To solve
the error, make sure the module has a named export and you aren’t mixing up
named and default exports and imports.