Build React components library with Webpack 4

后端 未结 2 1263
天命终不由人
天命终不由人 2021-02-07 15:19

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

相关标签:
2条回答
  • 2021-02-07 15:31

    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/

    0 讨论(0)
  • 2021-02-07 15:43

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

    /// Button.js
    import React from "react";
    
    const Button = () => <button>Foobar</button>;
    
    export default Button ;
    
    // index.js
    export { default as Button } 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.js
    export * 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.

    0 讨论(0)
提交回复
热议问题