尝试导入错误“X”未从#导出
Attempted import error ‘X’ is not exported from
当我们尝试导入指定文件中不存在的命名导入时,会出现 React.js“尝试导入错误‘X’未导出自”。要解决该错误,请确保模块具有命名导出并且您没有混淆命名导出和默认导出和导入。
下面是错误如何发生的示例。这是一个导出函数的文件。
// 👇️ Note: default export export default function sum(a, b) { return a + b; }
这是index.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”,请确保:
- 在导入时将命名的导出包在花括号中
default
将值导出为默认导出时使用关键字- 每个模块最多只有 1 个默认导出,但可以有多个命名导出
以下是如何使用命名导出解决错误的示例。
// 👇️ Using named export export function sum(a, b) { return a + b; }
并导入index.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.
// 👇️ default export export default function sum(a, b) { return a + b; }
And now we use a default import in the index.js
file.
// 👇️ 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.
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.
// 👇️ default export const example = 'hello world'; export default example;
You can also mix and match, here’s an example.
// 👇️ default export export default function sum(a, b) { return a + b; } // 👇️ named export export const num = 15;
And here are the imports.
// 👇️ 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.