How to publish a Reactjs component for npm

Purpose: I have a simple React component with two imports: reactand prop-types, and I'm trying to publish it before npm.

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

class MyComponent extends Component {
   ...
}

export default MyComponent;

Problem: I have never published anything before, so I'm not sure how to configure everything. Below I tried - when I test it with npm link, I can import the component successfully, but as soon as I try to use it, it causes the following error:

The element type is invalid: a string is expected (for built-in components) or a class / function (for composite components), but received: object. You probably forgot to export your component from the file that it defined, or you could have mixed up the default values ​​and named import.

File structure:

├── 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 file:

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, :

import MyComponent from 'my-component';
+4
1

webpack output.libraryTarget , webpack , :

  • "commonjs2": module.exports
  • "umd": , CommonJS, AMD script/ ( @JoeClay)

: https://webpack.js.org/configuration/output/#module-definition-systems

CommonJS, .

+1
source

Source: https://habr.com/ru/post/1691988/


All Articles