I'm trying to import a very simple component from a library into a Next.js app.
I have stripped down my library to the bare minimum. It contains the following src/components/index.js
:
import React from 'react'
const Container = ({ children }) => <div>{children}</div>
export { Container }
In my Next.js app, I created a pages/index.js
that contains the following:
import React from 'react'
import { Container } from 'mylib'
class HomePage extends React.Component {
render() {
return <Container>Hello</Container>
}
}
export default HomePage
mylib
is a local npm package which I have installed in my Next.js app using npm i ../mylib
. It has a standard webpack config:
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',
}
}
],
},
};
and then the package.json points to dist/components.js
as the main file.
The following does work:
- In my Next.js app, replace
return <Container>Hello</Container>
withreturn <div>Hello</div>
(while keeping theimport { Container }
in place) - Refresh the page in the server (I'm running Next's dev server)
- Restore the use of
<Container>
(the opposite of step 1) - Save the file --> hot-reload in the browser with the
Container
properly displayed (I added a className to be sure)
At this point, if I refresh the browser, I get the following error:
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.
which suggests I made a bad import/export, but I don't know where. And the error only occurs on the server-side.
What did I do wrong?