preface
I reference React components from various communities in my projects and encapsulate reusable components in my own projects, but I don’t know how to publish components to NPM. Recently, the project has a large demand for Toast. After searching, there is no lightweight component available, so I simply send one to NPM for practice.
To prepare
- Before writing a community component, the most important thing is to think about the API of the component first, because our component is for others to use, so how to use the most convenient and elegant, all need to be considered in advance. I believe that you have all encountered a component of the document search because of its long length and difficult to use and give up, so this is the most important point, with others and their convenience.
- Second, think of the name of the component. A simple and recognizable name is also one of the criteria for ease of use.
steps
This article only documents the steps I felt were critical at the time of publication, the full code can be viewed on my Github.
-
The two SRC folders hold the corresponding code for the component, usually a single-entry index.js and other sub-components. Example is a code example that uses components, usually in a static web page, to show the effects
-
The WebPack compilation component is based on es6 + JSX syntax, so compilation is inevitable. Since my project will eventually need to compile and deploy to Github Pages, I use two webPack configurations, one for local dev Server and one for deployment online. Only the local service configuration is posted below:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode: 'development'.entry: './example/src/index.js'.output: {
filename: '[name].bundle.js'.path: path.resolve(__dirname, 'dist')},devtool: 'cheap-module-source-map'.devServer: {
contentBase: './example'.compress: true.clientLogLevel: 'none'.hot: true.port: 3001
},
resolve: {
extensions: ['.js'.'.jsx']},module: {
rules: [{test: /\.(js|jsx)$/.exclude: /node_modules/.loader: 'babel-loader'.options: {
cacheDirectory: true}}, {test: /\.css$/.use: ['style-loader'.'css-loader']]}},plugins: [
new HtmlWebpackPlugin({
inject: true.template: path.resolve(__dirname, 'example/index.html')}),new webpack.HotModuleReplacementPlugin()
],
performance: false
};
Copy the code
Since my project only has CSS and JS and no other static resources such as images, I only need two simple Loaders and the rest reference as needed.
- Eslint code validation Code validation is now a standard part of front-end engineering, not only to catch low-level errors early, but also to standardize your code style, significantly improving the development experience. Here is my ESLint configuration file:
module.exports = {
// Code execution environment, such as the browser side can not prompt document, window and other global objects are not defined
env: {
browser: true.es6: true.node: true
},
plugins: ['react'].extends: ['eslint:recommended'.'plugin:react/recommended'].// React uses some syntax that is not in the ES standard, so it needs to be parsed by Babel
parser: 'babel-eslint'.parserOptions: {
sourceType: 'module'.ecmaFeatures: {
jsx: true}}};Copy the code
- Once the code for Babel is written and the tests are ok, how do you compile and publish the written modules? I searched a lot of articles directly packaged with Webpack and useful Babel CLI compiled, and then looked at the source of popular components in the community are directly compiled with Babel, so I referred to an article (see the end of the article) to open the manual.
Run the following command to install the required modules:
npm install --save-dev babel-cli babel-core babel-preset-env babel-preset-react-app
Copy the code
Babel configuration file:
{
"presets": ["env"."react-app"]}Copy the code
Finally, add this NPM script to package.json:
{
"scripts": {
"compile": "NODE_ENV=production babel src --out-dir lib"}}Copy the code
NODE_ENV=production the NODE_ENV=production statement is required by babel-react-app, which specifies the node environment for internal optimization; The Babel command compiles the code from the SRC folder to the lib directory on the same level. Now type NPM run compile on the command line to see the compiled code, which is the final component we publish to NPM.
- use
npm link
Test your component
Once your component is compiled, you can test it locally in other projects before publishing it to NPM. First of all inpackage.json
Specified component entry file in:
{
"main": "lib/index.js"
}
Copy the code
Then run NPM link so that your component is associated with the local global node_modules, then run NPM link light-toast in another project (instead of your component name), This allows you to import your components into local projects.
-
The Readme component is intended for use by yourself and others, so a concise and easy to understand Readme is essential. As a window into your code for others, be sure to write it in a simple way. A long description document will instantly reduce one’s interest in using the component.
-
First we need a.npmignore file to specify which files do not need to be published to NPM.
example
src
.babelrc
.eslintrc.js
.gitignore
.prettierignore
webpack.config.js
webpack.config.prod.js
Copy the code
Second, add a LICENSE file, as for why this is necessary to understand the react protocol caused by the unpleasant, but open source most use MIT protocol, directly find a ready-made copy of it.
Then, modify the script we just wrote:
{
"scripts": {
"prepublishOnly": "NODE_ENV=production babel src --out-dir lib"}}Copy the code
PrepublishOnly is a hook provided by NPM that is executed before NPM publish so that we can automatically compile the code every time we publish.
Change the dependencies in package.json, such as component version number, keyword, git repository, etc. Most importantly, move the react and react-dom dependencies to peerDependencies.
Now you can finally publish your first React component! To publish, you need to register an NPM account, run NPM adduser and publish, and you will find your own components in the NPM repository
- Host the demo using Github Pages
If your project is a UI component, it’s a good idea to provide an online preview address so that others can see how it works, which will also be a big plus for your project. Let’s say the directory for our packaged static demo is under dist and contains oneindex.html
Template and oneindex.js
Entry, runnpm install --save-dev gh-pages
This is a package that pushes our code into the GH-Pages branch. Then, inpackage.json
Add the following script to:
{
"scripts": {
"deploy": "gh-pages -d dist"}}Copy the code
To publish demo to Github Pages, run NPM run deploy.
conclusion
This post is my first post on the React component, and I’ve searched a lot of resources to help you avoid missteps and contribute more to the open source community.
If you’re looking for a small Toast component that doesn’t require any additional styling, this is the person for you.
Reference article: Lessons Learned From Publishing a React Component to npm A guide to building a React component with webpack 4, publishing to npm, and deploying the demo to GitHub Pages