Skip to content

How to publish your React component on npm

tutorial, npm, react3 min read

This tutorial is for the more experienced React developers. If you’re just looking to learn how to build a React app, there are tons and tons of tutorials available online!

Ok, so you’ve read tutorials, figured out how to set up a React project using create-react-app, learned how to install npm packages, and finally created your very own functional React app, and to that that I say congratulations!

alt text

As you go on your journey of creating your apps, you will undoubtedly come across some cool open source npm packages that made your development easier, whether it be material-ui, react-router, or react-spinners. Heck, chances are you might’ve even come up with some of your own cool React components! And now you’re wondering, how might I share that with the rest of the world?


Packaging your React component

Before publishing anything to npm, the first step is to put your component files into a nice, clean package. I’ve created a template to make everything easier to follow, go ahead and download this first. And once you’re done, open the folder in your favorite code editor.

alt text

my favorite one is definitely Visual Studio Code

1. Adding your React component

The first thing you’re gonna wanna do is to move your React component files into the /src folder. For the purpose of this demonstration, I’ve created a component called MyCoolButton.js . Make sure to also include all the files that are required by your component. In this case, I‘ve also added in MyCoolButton.css .

alt text

Add your component files into /src folder

2. Sort out dependencies

The next thing you have to do is to figure out if your component requires any other dependencies. You can find that out by opening up your component file and check if it imports any other dependencies. In this case, my component requires the dependency prop-types .

1// This component also requires 'react',
2// but it has already been included in the
3// list of dependencies in package.json
4import React from 'react';
5
6// This component requires prop-types
7import PropTypes from 'prop-types';
8
9import './MyCoolButton.css';
10
11const MyCoolButton = ({ type, title, onClick }) => (
12 <button
13 type={type}
14 className="container"
15 onClick={onClick}
16 >
17 {title}
18 </button>
19);
20
21MyCoolButton.propTypes = {
22 title: PropTypes.string.isRequired,
23 type: PropTypes.string,
24 onClick: PropTypes.func,
25};
26
27MyCoolButton.defaultProps = {
28 type: 'button',
29 onClick: () => {},
30};
31
32export default MyCoolButton;

Now let’s open up package.json , and add the dependencies in. Normally you would add your dependencies under dependencies , but in this case, you have to add them into peerDependencies and devDependencies . This is how your package.json should look like. Notice that the list of dependencies is empty

1{
2 "name": "YOUR_PACKAGE_NAME",
3 "version": "0.0.1",
4 "description": "",
5 "main": "./lib/YOUR_COMPONENT.js",
6 "license": "MIT",
7 "scripts": {
8 "build": "webpack"
9 },
10 "peerDependencies": {
11 "prop-types": "^15.6.0",
12 "react": "^16.0.0",
13 "react-dom": "^16.0.0"
14 },
15 "devDependencies": {
16 "prop-types": "^15.6.0",
17 "babel-core": "^6.21.0",
18 "babel-loader": "^7.1.4",
19 "babel-preset-env": "^1.6.1",
20 "babel-preset-react": "^6.16.0",
21 "babel-preset-stage-0": "^6.24.1",
22 "css-loader": "^3.5.1",
23 "path": "^0.12.7",
24 "react": "^16.0.0",
25 "react-dom": "^16.0.0",
26 "style-loader": "^1.1.3",
27 "webpack": "^4.5.0",
28 "webpack-cli": "^3.2.1"
29 },
30 "dependencies": {}
31}

After that, run npm install (or if you use yarn, yarn install) to install the required dependencies.

3. webpack.config.js

Next up, we’ll use Webpack to bundle our React components into a nice CommonJS module. Click here to learn more about Webpack and what it does. Let’s start by opening up webpack.config.js .

1const path = require('path');
2
3module.exports = {
4 mode: 'production',
5 entry: './src/MyCoolButton.js',
6 output: {
7 path: path.resolve('lib'),
8 filename: 'MyCoolButton.js',
9 libraryTarget: 'commonjs2',
10 },
11 module: {
12 rules: [
13 {
14 test: /\.js?$/,
15 exclude: /(node_modules)/,
16 use: 'babel-loader',
17 },
18 {
19 test: /\.css$/,
20 use: [
21 'style-loader',
22 'css-loader'
23 ]
24 }
25 ],
26 },
27 resolve: {
28 alias: {
29 'react': path.resolve(__dirname, './node_modules/react'),
30 'react-dom': path.resolve(__dirname, './node_modules/react-dom'),
31 }
32 },
33 externals: {
34 // Don't bundle react or react-dom
35 react: {
36 commonjs: "react",
37 commonjs2: "react",
38 amd: "React",
39 root: "React"
40 },
41 "react-dom": {
42 commonjs: "react-dom",
43 commonjs2: "react-dom",
44 amd: "ReactDOM",
45 root: "ReactDOM"
46 }
47 }
48};

This is the file that contains the different configurations that Webpack will use to bundle your React component. Here’s a description of the important settings:

entry — This refers to your React component. You should change it to the component that you’ve added in Step 1.

output — This specifies the path to the output file. You should update the filename to match your component’s file name.

module.rules — This is an array of rules that we are applying to our module. The first rule looks for any .js file and tries to transpile it using babel-loader . However, the second rule is only relevant if your component uses css . If your component uses any css, you will have to add this in. Click here to find out more about [css-loader](https://webpack.js.org/loaders/css-loader/) and [style-loader](https://webpack.js.org/loaders/style-loader/) .

Important Note

If your component uses .sass or.scss , you would have to also include [sass-loader](https://webpack.js.org/loaders/sass-loader) by adding it to your Webpack module rules as well as adding it to your list of devDependencies in package.json . Click here to see a list of loaders that you might need to use.

I have only gone through the options that are relevant to this tutorial. Check out the full list of options here.

4. Bundle em’ up

Run npm run build (or if you use yarn, yarn build). This should generate a folder called /lib which contains your freshly packaged component, in this case, MyCoolButton.js .

5. Test your component

Before you publish it to the world, it would make sense to take your package for a test drive first (or if you’re absolutely confident that it will work, feel free to skip ahead to Publishing To NPM).

Run npm pack . This will generate a .tgz file at the root directory.

Open up any React application that you want to test your new package, and then run npm install path_to_tgz_file . Replace path_to_tgz_file with your actual path.

In my case, the whole command looks like this: npm install /Users/Groftware/mycoolbutton/mycoolbutton-0.0.1.tgz .

The next thing you do is just import the component and use it normally

1import React from 'react';
2import MyCoolButton from 'mycoolbutton';function App() {
3 return (
4 <div>
5 <MyCoolButton title="Click Me!"/>
6 <div>
7 )
8}export default App;

Does it work? Great! Let’s move on to actually publishing it to the world.

Publishing to NPM

Alright so now you have your /lib folder with your newly packaged component ready to go, the next thing to do it just publishing it to npm.

Run npm login and login with your npm account. Create one here if you don’t already have one.

After you’re logged in, the final thing to do is npm publish , and you’re all set!


Links

Tutorial Template and complete example

React

Npm

Yarn

Webpack


Enjoyed or found this helpful? Checkout my other articles here. Thanks!

Enjoyed this article?

Are you ready to go to the next level? 🚀 Register to our newsletter now to receive freshly brewed software development, design, and business articles and tips, right to your inbox! 📥
Our promise to you: No spam, just great articles.
© 2020 by blog.groftware.tech. All rights reserved.