Those of you who have never released an NPM package may be in awe of NPM’s approach to development and feel that it is a high-class thing. There was even an interview where the interviewer asked me if I had ever sent NPM package, but I only used it and didn’t write it. I thought it would be very difficult, so I whispered no and then let me go back.

In fact, in my opinion, THE NPM package is just an export module that we often write, but it has low coupling with other business codes and high independence. Of course, to publish an NPM package, you need to do some basic packaging work in addition to writing module components. Here I will take the recently developed react-loading component as an example of the source address, if it is helpful to you, I hope you don’t skint your Star

This article describes how to develop the React component (react-Loding as an example) and publish it on NPM. Without further ado, let’s get to the point

Create components

Create a project repository and initialize it

Create a new repository on Github with your own name. Make sure you create a component name that has never been used in NPM, using wSM-loading as an example. Open the editor to pull the project to your local and initialize it

git clone https://github.com/xxx/wsm-loading.git
cd wsm-loading
npm init
Copy the code

Run NPM Init the list of questions can be filled in according to your personal preference, or you can take the default option.

Install project dependencies

We need to develop a React loading component, so we need to install the React dependency in our project first

npm i react react-dom -D

Our project will be built with WebPack 4, installing the WebPack dependencies required for the project

npm i webpack webpack-cli webpack-dev-server html-webpack-plugin style-loader css-loader babel-core babel-loader babel-preset-env babel-preset-react -D

We often use SCSS as a compilation of CSS in our projects, so we are installing webPack

npm install sass sass-loader node-sass webpack -D

Now that the dependencies installed above have been added to package.json in the root directory, we add a start script to start our locally developed server as follows:

{
 "name": "wsm-loading"."version": "0.0.1"."description": "This is a react-loading component"."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."start": "webpack-dev-server --mode development",},Copy the code

Developing loading components

Now let’s create a directory of components and sample code in our project with the following tree structure

├ ─ ─ examples / / sample code storage directory │ └ ─ ─ the SRC ├ ─ ─ node_modules ├ ─ ─ package. The json └ ─ ─ SRC / / component source code and style store directory └ ─ ─ the babelrc / / es6 and JSX grammar compiler ├ ─ garbage, └─ package-lock, └─ download.txtCopy the code

The lodaing component receives two props, one size to control the size of loading and one color to control the color of loading

/*** src/index.js  ***/
import React, { Component } from "react";
import "./index.scss";
export default class MyComponent extends Component {
  render() {
    const { color, size } = this.props;
    const sizeStyle = {
      width: `${size}px`,
      height: `${size}px`
    };
    const colorStyle = {
      border: `1px solid ${color}`,
      borderColor: `${color} transparent transparent transparent`
    };
    const ringStyle = Object.assign({}, colorStyle, sizeStyle);

      return (
      <div className="loading" style={sizeStyle}>
        <div className="loading__ring" style={ringStyle} />
        <div className="loading__ring" style={ringStyle} />
        <div className="loading__ring" style={ringStyle} />
      </div>
    );
  }
}
MyComponent.defaultProps = {
    size: '36',
    color: '# 000'
  }
Copy the code

The loading component styles are not given here, but can be copied directly from my code base to your project CSS.

Next, let’s add a demo

<! -- examples/src/index.html --> <html> <head> <title>My Component Demo</title> <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
 <div id="root"></div>
</body>
</html>
Copy the code
/*** examples/src/index.js ***/
import React from 'react';
import { render} from 'react-dom';
import MyComponent from '.. /.. /src';
const App = () => (
 <MyComponent size='36' color='red' />
);
render(<App />, document.getElementById("root"));
Copy the code

Loading component optimization

This is a basic loading component, but we still have a question. Loading is now introduced in the root element, and some widely used UI frameworks do have loading components in the body layer, no matter where you introduce them. This prevents the loading component from being disturbed by its parent’s style.

Create a newPortal/ newportal. js file in SRC

import React from 'react';
import ReactDOM from 'react-dom';

class NewPortal extends React.Component {
  constructor(props) {
    super(props)
    this.node = document.createElement('div');
    document.body.appendChild(this.node);
  }
  render() {
    const { children } = this.props;
    returnReactDOM.createPortal( children, this.node, ); }}export default NewPortal
Copy the code

Introduce this into our loading component

import NewPortal from ‘./newPortal/newPortal’

And wrap the components in a layer

  <NewPortal>
    <div className="loading" style={sizeStyle}>
      <div className="loading__ring" style={ringStyle} />
      <div className="loading__ring" style={ringStyle} />
      <div className="loading__ring" style={ringStyle} />
    </div>
  </NewPortal>
Copy the code

Here the author optimizes the component with reference to this article. If you are interested, you can go to learn about it.

Configuration webpack

Next configure webpack by creating the webpack.config.js file under the project root. For those who are not familiar with webpack configuration, please refer to my previous article webpack configuration in detail.

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebpackPlugin({
  template: path.join(__dirname, "examples/src/index.html"),
  filename: "./index.html"
});
module.exports = {
  entry: path.join(__dirname, "examples/src/index.js"),
  output: {
    path: path.join(__dirname, "examples/dist"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: "babel-loader",
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: ["style-loader"."css-loader"] {},test: /\.scss$/,
        use: ["style-loader"."css-loader"."sass-loader"]
      }
    ]
  },
  plugins: [htmlWebpackPlugin],
  resolve: {
    extensions: [".js".".jsx"]
  },
  devServer: {
    port: 3001
  }
};

Copy the code

Configuration babelrc

The JSX files used in React need to be compiled and converted to ES5, which is supported by all major browsers. The common configuration is simple: add a pair of presets and add the files to the project root directory

{
 "presets": ["env"."react"]}Copy the code

So let’s run demo

You can modify your code and save it. The page will be refreshed automatically. Our development environment has been put into monitoring mode

Publish to NPM

We want to release the compiled and compressed version of Babel, so that projects that don’t use Babel can still use it, such as no JSX syntax. First, you need to install the Babel CLI

npm i babel-cli -D

Now we add transpile scripts to compile our source code using Babel, copy some static files (such as CSS files) to the destination package directory dist and specify the compiled version as the main entry for the component. The changed package.json looks like this

{
  "name": "test"."version": "1.0.0"."description": "ceshi"."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."start": "webpack-dev-server --mode development"."transpile": "babel src -d dist --copy-files"
  },
Copy the code

Try to compile

npm run transpile

Finally, let’s add the.npmignore file at the root of the project to tell NPM which files and folders in our project were ignored in the distributed package

# .npmignore 
src
examples
.babelrc
.gitignore
webpack.config.js
Copy the code

Publish our components to NPM

npm publish

Before submitting NPM, you need to open your own account on NPM and verify your email address, so as to submit it normally. Use NPM login to login your information on the terminal

Upload the code to Git

Before you upload your project to Git, you need to configure.gitignore and add the.npmignore file in the root directory of your project

# .gitignore
node_modules
dist
Copy the code

So when we upload, we don’t upload the node_modules and dist directories

git add .
git commit -m 'the react - loading components'
git push
Copy the code

After the language

While we are constantly stuck in business code development, why not take some time out to do something we love, such as taking our business components and turning them into an NPM? Open source component library can not only improve ourselves but also reach out to things we would otherwise not have access to. This is just a simple tutorial that I hope will inspire you.

Thanks for reading!