gpt4 book ai didi

javascript - 无法在服务器端 Next.js 上导入 React 组件

转载 作者:行者123 更新时间:2023-12-05 08:07:17 25 4
gpt4 key购买 nike

我正在尝试将一个非常简单的组件从库中导入到 Next.js 应用中。

我已将我的图书馆精简到最低限度。它包含以下 src/components/index.js :

import React from 'react'
const Container = ({ children }) => <div>{children}</div>
export { Container }

在我的 Next.js 应用程序中,我创建了一个 pages/index.js包含以下内容:

import React from 'react'
import { Container } from 'mylib'

class HomePage extends React.Component {
render() {
return <Container>Hello</Container>
}
}

export default HomePage

mylib是一个本地 npm 包,我使用 npm i ../mylib 安装在我的 Next.js 应用程序中.它有一个标准的 webpack 配置:

const path = require('path')

module.exports = {
entry: {
components: './src/components/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
libraryTarget: 'commonjs2'
},
mode: "production",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
}
}
],
},
};

然后 package.json 指向 dist/components.js作为主文件。

以下确实有效:

  1. 在我的 Next.js 应用中,替换 return <Container>Hello</Container>return <div>Hello</div> (同时保持 import { Container } 到位)
  2. 刷新服务器中的页面(我正在运行 Next 的开发服务器)
  3. 恢复使用 <Container> (与步骤 1 相反)
  4. 保存文件 --> 使用 Container 在浏览器中热重载正确显示(我添加了一个类名以确保)

此时,如果我刷新浏览器,会出现以下错误:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

这表明我导入/导出错误,但我不知道在哪里。并且错误只发生在服务器端。

我做错了什么?

最佳答案

容器应该是默认导出的,所以这样:

import React from 'react'

const Container = ({ children }) => <div>{children}</div>

export { Container }

应该是这样的:

import React from 'react'

const Container = ({ children }) => <div>{children}</div>

export default Container

您也可以像这样单行 Container 组件:

import React from 'react'

export default Container = ({ children }) => <div>{children}</div>

关于javascript - 无法在服务器端 Next.js 上导入 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55323226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com