【问题标题】:Nextjs import export modules in one lineNextjs 一行导入导出模块
【发布时间】:2020-11-29 17:17:46
【问题描述】:

我正在开发一个 NextJs 应用程序,我有一个带有 Header.jsx 的标题文件夹和一个默认导出 Header

在同一个文件夹中,我有一个带有此代码的 index.js

export * from './Header'

但如果我使用它,它会失败并出现错误

Attempted import error: '../components/header' does not contain a default export (imported as 'Header').

如果我用这个

import Header from './Header'

export default Header

它工作正常。有没有办法在 NextJs 中使用单行导出来避免这种重复?

谢谢

【问题讨论】:

  • 你的头文件的导入和导出看起来在同一个代码块中,这让我有点困惑,你是说你是从其他文件导出还是从同一个文件导入/导出。
  • 这能回答你的问题吗? ES6 exporting/importing in index file
  • 在 next.js 中的组件应该使用 export default 导出

标签: javascript babeljs next.js es6-modules


【解决方案1】:

导出与默认导出

  • ES6 提供了两种从文件中导出模块的方法:命名导出和默认导出。
  1. 命名导出:(导出)

    • 您可以在一个文件中拥有多个命名导出
    // File ./AllComponents.js
    
    export const Comp1= () => {}
    export const Comp2= () => {}
    
    //File ./SomeComponent.js
    // ex. importing a single named export
    import { Comp1 } from "./AllComponents";
    // ex. importing multiple named exports
    import { Comp1, Comp2} from "./AllComponents";
    // ex. giving a named import a different name by using "as":
    import { Comp1 as MyCustomName } from "./AllComponents";
    
  • 您可以将所有这些作为一个对象导入

    import * as MainComponents from "./AllComponents";
    // use MainComponents.Comp1 and MainComponents.Comp2
    

默认导出:(导出默认)

  • 每个文件可以有一个默认导出。
  • 导入的时候,我们要做如下操作
// File 1: create and export MyComponent
//create a component
const MyComponent = () => {}
//export it
export default MyComponent;

// File 2: import the component in some File
import DefaultExportFromAComponent from "./DefaultExportFromAComponent";

【讨论】:

  • 我想要做的是使用加载模块的索引文件。所以 Header 有自己的文件,但是其他组件会用./header 加载它,因为它是在索引中导出的。所以在索引中导入 Header 并在一行中导出
  • stackoverflow.com/questions/34072598/… 这可能会回答你的问题。
猜你喜欢
  • 2021-11-23
  • 2021-12-29
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 2016-06-10
相关资源
最近更新 更多