Webpack bundle not exporting React Component

Viewed 520

I am building a frontend package that will export out 1 React component for other packages to import and render. I am trying to use webpack to bundle my React component however I can't seem to get my component to be exported from the bundle.

I am testing the bundle by importing the dist/bundle directly into a storybook story to render out.

Here is a naive example of what I'm trying to do:

// index.js

import React from "react";

export const ComponentToExport = () => <h1>Hello World!</h1>;
// webpack.config.js

const path = require("path");

module.exports = {
  entry: "./app/index.js",

  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
    libraryTarget: "umd",
  },

  module: {
    rules: [
      {
        // transpile with babel
        test: /\.(js|jsx)?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
};

I then run webpack --mode development which produces the bundle, dist/bundle.js.

I have a story in storybook I'm trying to import the bundle from dist and render it:

// app.stories.js

import React from "react";
import { ComponentToExport } from "../dist/bundle.js";
console.log("ComponentToExport: ", ComponentToExport);

export default { title: "RemoteComponentExample" };

export const example = () => (<ComponentToExport />);

I expect a story with "Hello World" to be printed on the page however I am seeing this error:

React.createElement: 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.

enter image description here

Also in the console.log(ComponentToExport) statement in my story, I am getting undefined returned in my dev tools.

I don't believe the component is being exported from dist/bundle.js. I've tried changing the libraryTarget in the webpack config along with adding/removing some other options however nothing seems to work.

What should be changed in my webpack config so that the bundle properly exports the ComponentToExport component so it can be imported in other files, and eventually consumed by other packages?

0 Answers
Related