Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't import the named export from non EcmaScript module (only default export is available) 问题 #701

Open
981377660LMT opened this issue Jan 22, 2025 · 2 comments

Comments

@981377660LMT
Copy link
Owner

@981377660LMT
Copy link
Owner Author

这个错误信息表示你尝试从一个非 EcmaScript 模块中导入命名导出,但该模块只提供默认导出。具体原因可能包括:

  1. 模块格式不兼容:目标模块使用 CommonJS(如 module.exports)而不是 ES6 模块语法。
  2. 导入语法错误:使用了 ES6 的命名导入语法 (import { something } from 'module') 来导入一个只支持默认导出的模块。
  3. 构建工具配置问题:如 Babel 或 webpack 的配置未正确处理模块转换,导致导入方式不匹配。

解决方法

  • 使用默认导入语法:
    import something from 'module';
  • 如果必须使用命名导出,可以在导入时进行解构:
    const something = require('module').something;
  • 检查并调整构建工具的配置,确保正确处理 CommonJS 和 ES6 模块之间的转换。

@981377660LMT
Copy link
Owner Author

这段代码用于配置 Webpack 以正确处理 .mjs 文件,具体解释如下:

webpackConfig.module.rules.push({
    test: /\.mjs$/,
    include: /node_modules/,
    type: 'javascript/auto'
});

作用说明

  1. 测试文件类型 (test)

    • 匹配所有扩展名为 .mjs 的文件。.mjs 通常用于表示 ES6 模块。
  2. 包含目录 (include)

    • 仅应用于 node_modules 目录下的 .mjs 文件。这意味着只对第三方库中的 .mjs 文件进行处理,避免影响项目自身的模块。
  3. 模块类型 (type)

    • 设置为 'javascript/auto',这允许 Webpack 自动决定如何处理这些文件。
    • 具体来说,'javascript/auto' 类型使 Webpack 同时支持 ES 模块和 CommonJS 模块的导入方式,解决了在某些情况下导入命名导出时出现的问题。

解决的问题

在一些使用 CommonJS 导出的模块中,如果尝试使用 ES6 的命名导入语法(import { something } from 'module'),可能会导致以下错误:

Can't import the named export from non EcmaScript module (only default export is available

通过设置 type: 'javascript/auto',Webpack 能够正确解析这些模块,允许混合使用 ES6 和 CommonJS 的导入方式,从而避免上述错误。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant