Skip to content Skip to sidebar Skip to footer

Build React Components Library With Webpack 4

I'm currently building a library of React components and bundling it with Webpack 4. Everything works just fine from building the library's bundle to publishing it on an npm regist

Solution 1:

You're exporting your library as commonjs and trying to import it via import/export syntax. You should change your output to

output: {
  filename: "index.js",
  path: path.resolve(__dirname, "dist"),
  libraryTarget: "umd",
  library: "my-design-system"
}

Found a lot of info here: https://webpack.js.org/guides/author-libraries/

Solution 2:

What I would do is to export your components as default and then re-export as named from index.js:

/// Button.jsimportReactfrom"react";

constButton = () => <button>Foobar</button>;

exportdefaultButton ;
// index.jsexport { defaultasButton } from"./src/components/Button";

Then you can do

import { Button } from"my-design-system";

Also make sure you have main set up, pointing to your index.js, in your design system's package.json

Additionally, if you still want to have named exports in some of your components, you can export everything from that component file:

//index.jsexport * from"./src/components/ComponentWithNamedExports";

Either way you will make sure there's always one point of export for all your components.

EDIT: As noted in by Maaz Syed Adeeb, you have wrong libraryTarget in your config. I'd remove both libraryTarget and library from there.

Post a Comment for "Build React Components Library With Webpack 4"