使用Webpack导出React库:找不到导出MyComponent

时间:2019-04-26 10:00:13

标签: javascript reactjs webpack babeljs node-modules

我正在使用Webpack 4.30.0,Babel 7和React来构建 lib (由于使用了Storybook,它可以在本地使用)。我将在其他地方使用此库。这是我使用的构建配置:

.babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

package.json(示例)

{
  "name": "mylib",
  "version": "1.6.0",
  "main": "dist/main.js",
  "scripts": {
    "build": "webpack --mode production"
  }
}

webpack.config.js

const path = require("path");
module.exports = {
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist/"),
    publicPath: "",
    filename: "main.js",
    libraryTarget: "umd",
    umdNamedDefine: true,
    globalObject: "typeof self !== 'undefined' ? self : this"
  },
  externals: [
    {
      react: {
        root: "React",
        commonjs2: "react",
        commonjs: "react",
        amd: "react"
      },
      "react-dom": {
        root: "ReactDOM",
        commonjs2: "react-dom",
        commonjs: "react-dom",
        amd: "react-dom"
      }
    }
  ]
};

src / index.js

import MyComponent from "./MyComponent";
// ...

export {
  MyComponent,
  // ...
}

当我尝试将此库导入其他地方(在另一个项目中)时,它失败(“未找到导出MyComponent”或“未定义”)。

import { MyComponent } from "react-elasticsearch"; // FAILS

我该怎么做才能使导出正常工作?

0 个答案:

没有答案