Hey guys, I’m stuck with a problem. I’m trying to make my own React component library as an npm package. I’ve set up the project structure, but I’m having trouble importing the components in other projects.
Here’s what I’ve done:
- Created a library with a simple
HelloWorld
component
- Set up webpack to bundle everything
- Used
npm pack
to create the package
- Installed it in another project
But when I try to use the component, I get errors about invalid element types. I’ve tried a few things:
import HelloWorld from 'my-cool-library';
// This doesn't work
<HelloWorld />
I also tried updating my webpack config with library options:
output: {
library: 'my-cool-library',
libraryTarget: 'umd'
}
Now I can use it like this:
import MyCoolLibrary from 'my-cool-library';
const HelloWorld = MyCoolLibrary.HelloWorld;
But that’s not ideal. What I really want is:
import { HelloWorld, AnotherComponent } from 'my-cool-library';
Any ideas on how to achieve this? I feel like I’m missing something obvious. Thanks!
I’ve encountered similar challenges when developing component libraries. One crucial aspect you might want to consider is properly configuring your babel.config.js file. Ensure you have the necessary presets and plugins, particularly @babel/preset-react and @babel/preset-env.
Additionally, double-check your package.json. Make sure you’ve specified the correct entry points:
"main": "dist/index.js",
"module": "dist/index.esm.js",
"files": ["dist"]
Lastly, in your src/index.js, export all components like this:
export { default as HelloWorld } from './components/HelloWorld';
export { default as AnotherComponent } from './components/AnotherComponent';
This setup should allow for the clean import syntax you’re aiming for. Remember to rebuild and republish your package after making these changes.
I’ve been down this road before, and it can be frustrating. One thing that helped me was using Rollup instead of Webpack for bundling. It’s better suited for libraries and handles tree-shaking more efficiently.
In your rollup.config.js, you can set it up like this:
export default {
input: 'src/index.js',
output: [
{ file: 'dist/index.js', format: 'cjs' },
{ file: 'dist/index.esm.js', format: 'es' }
],
external: ['react']
}
Then in your package.json, add:
"main": "dist/index.js",
"module": "dist/index.esm.js",
This approach worked wonders for me. It allowed for both CommonJS and ES module imports, which is crucial for compatibility. Give it a shot and see if it resolves your issues!
hey mate, i had similar issues. try tweaking ur package.json:
"main": "dist/index.js",
"module": "dist/index.es.js",
Then export components in index.js:
export { default as HelloWorld } from './components/HelloWorld';
this shud let u import components directly. good luck!