简体   繁体   中英

importing a component shared via npm throwing error

I am trying to export a component to npm and then import in my react application

my export application webpack config looks like this

const path = require('path');

module.exports = {
  entry: path.resolve(__dirname, './src/export.js'),
  mode: "production",
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: 'css-loader'
          }
        ],
      },
    ]
  },
  resolve: {
    extensions: ['.js']
  },
  externals: {
    'react': 'react',
    'react-dom': 'react-dom'
  },
  output: {
    path: path.resolve(__dirname, './dest'),
    filename: 'bundle.js',
  },
  devServer: {
    static: path.resolve(__dirname, './dist'),
  },
};

My export.js file looks like this

import Checkbox from './components/Checkbox/Checkbox';

export {
    Checkbox
}

It creates a bundle.js file which is then imported in another react application.

import Checkbox from "common_ui_utils";
export default function App() {
  return (
    <>
      <h1>Hello!</h1>

      <Checkbox />

    </>
  );
}

Checkbox component look like this

import React from 'react';
import PropTypes from 'prop-types';
import './style.css';

function Checkbox(props) {
   --Checkbox code here --
}

I am getting this error while react is working perfectly fine in that repo

在此处输入图像描述

Referring to this answer can you try this in your webpack config file

externals: {
    'react': 'React'
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM