如何将Reactjs组件发布到npm

时间:2018-01-10 16:04:53

标签: reactjs npm webpack package.json

目标:我有一个简单的React组件,其中包含两个导入:reactprop-types,我试图将其发布到npm。

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

class MyComponent extends Component {
   ...
}

export default MyComponent;

问题:我之前从未发布任何内容,所以我不确定如何设置所有内容。以下是我尝试过的内容 - 当我尝试使用npm link进行测试时,我可以成功导入该组件,但是一旦我尝试使用它,它就会出现以下错误:

  

元素类型无效:需要一个字符串(用于内置组件)   或类/函数(对于复合组件)但得到:对象。您   可能忘记从您定义的文件中导出组件,   或者您可能混淆了默认导入和命名导入。

文件结构:

├── 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';

1 个答案:

答案 0 :(得分:1)

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

  • "commonjs2":您的入口点的返回值将分配给module.exports
  • "umd":构建适用于CommonJS,AMD和老式脚本标记/全局变量的构建(归功于@JoeClay

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

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