如何将Reactjs组件发布到npm

目标:我有一个简单的React组件,有两个导入:react和prop-types,我正在尝试将它发布到npm.

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class MyComponent extends Component {
   ...
}

export default MyComponent;

问题:我以前从未发表任何内容,所以我不确定如何设置一切.下面是我尝试过的 – 当我尝试使用npm链接测试它时,我可以成功导入组件但是一旦我尝试使用它,它就会给我以下错误:

Element type is invalid: expected a string (for built-in components)
or a class/function (for composite components) but got: object. You
likely forgot to export your component from the file it’s defined in,
or you might have mixed up default and named imports.

文件结构:

├── node_modules/
├── lib/
|   ── index.js    <--- this is where webpack builds to
├── src/
|   ── index.js    <--- this is the react component
|
├── package.json
├── webpack.config.js
├── .babelrc
├── .npmignore
├── .gitignore

的package.json:

{
  "name": "...",
  "version": "1.0.0",
  "description": "...",
  "main": "lib/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack-dev-server --open"
  },
  "repository": {
    "type": "git",
    "url": "..."
  },
  "author": "...",
  "license": "MIT",
  "bugs": {
    "url": "..."
  },
  "homepage": "...",
  "dependencies": {
    "prop-types": "^15.0.0"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "webpack": "^3.10.0",
  },
  "peerDependencies": {
    "react": "^15.0.0 || ^16.0.0",
    "react-dom": "^15.0.0 || ^16.0.0"
  }
}

webpack文件:

const path = require('path');

module.exports = {
  entry:  './src/index.js',
  output: {
    path: path.resolve(__dirname, 'lib'),
    filename: 'index.js'
  },
  module: {
    rules: [
      {
        test: /\.(js)$/,
        use: 'babel-loader'
      }
    ]
  },
  externals: {
    'react': 'commonjs react',
    'react-dom' : 'commonjs react-dom'
  }
};

.babelrc:

{
  "presets": ["env", "react"],
  "plugins": ["transform-class-properties", "transform-object-rest-spread"]
}

输入:

而且,为了澄清,我没有混合默认和命名导入,该包被导入为默认导入:

import MyComponent from 'my-component';

最佳答案 webpack配置选项output.libraryTarget可用于告诉webpack它应该创建的构建类型:

>“commonjs2”:输入点的返回值将分配给module.exports
>“umd”:导致与CommonJS,AMD和老式脚本标签/全局变量一起使用的构建(信用到@JoeClay)

请参阅此处的文档:https://webpack.js.org/configuration/output/#module-definition-systems

这些设置会将组件导出为可以根据需要导入的CommonJS模块.

点赞