npm: the whole process of publishing components to npm (using rollup packaging tool)

Posted by madan koshti on Mon, 27 Sep 2021 05:28:34 +0200

There are few tutorials of self-made npm package on the Internet, and there are many difficulties, so I made this video so that we don't have to climb the pit again. Self made front-end plug-ins and published to npm generally need packaging tools, because npm itself runs in node, and node does not support es6 import syntax, while front-end packages generally use import syntax for modularization, so we need to use packaging tools + babel.

npm for beginners

If you think the pace of this article is too fast to adapt, you can take a look at these articles first

npm (I): start with npm CLI_ Five tigers war painting halberd - CSDN blog

npm (II): analyzing package.json_ Five tigers war painting halberd - CSDN blog

npm (III): release, update and discard of npm package_ Five tigers war painting halberd - CSDN blog

It introduces the npm command line, package.json and basic npm contracting process in detail in a novice friendly way. After reading these articles, I believe you will be much clearer after reading this article!

1. New project

$ mkdir my-first-npm-lib
$ cd my-first-npm-lib
$ npm init -y

2. Installation dependency

2.1 package with rollup

$ yarn add rollup -D

2.2 use rollup plugin Babel to compile es syntax into es5 when rollup is packaged

$ yarn add rollup-plugin-babel -D

2.3 installation of babel

$ yarn add @babel/core @babel/preset-env @babel/preset-react -D

3. Project directory structure

3.1 create in root directory   src directory as source directory

$ mkdir src

three point two   Create at root   The lib directory stores the packaged files

$ mkdir lib

3.3 in   src   Create a new directory, index.js, as the entry file, and a new Components folder to write our Components

$ touch index.js
$ mkdir Components

3.4 create a new Image folder in the Components directory and index.jsx under Image

$ touch index.js
$ cd Components && mkdir Image
$ cd Image && touch index.jsx

3.5 create. yarnignore to ignore some files and write ignored content when publishing npm

$ touch .yarnignore
src
.gitignore

4. Configure Rollup   Rollup.js Chinese document | rollup.js Chinese website

4.1 create rollup.config.js in the root directory  

$ touch rollup.config.js

4.2 its configuration can be viewed in the rollup document

Configuration file | rollup.js Chinese document | rollup.js Chinese website

Core function | rollup.js Chinese document | rollup.js Chinese website

We only need to configure the required items and configure the core functions here

import babel from 'rollup-plugin-babel'

export default {
  input: './src/index.js', // Entry file
  output: {
    file: './lib/bundle.js', // Export documents
    format: 'cjs' // Output module syntax format
  },
  plugins: [babel()]
}

For synchronization, you need to change the main of your package.json to the export file path

{
  "main": "lib/bundle.js"
}

4.3 start packaging and optimize configuration

Try writing some code in the Image component

// Image/index.jsx
import React from 'react'

export default () => {
  return(
    <h1>Image assembly</h1>
  )
}

Thrown in index.js

import Image from './Components/Image/index.jsx'

export { Image }

Package and test with rollup

$ yarn run rollup -c

You will find that the report is wrong

  This is because we have no configuration   babel makes rollup unable to understand jsx syntax. Just configure babel

// .babelrc
{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

  Execute the package command again

$ yarn run rollup -c

  You can see that the package is successful. Take a look at the bundle.js under lib

  But if you see a warning here, just follow the prompts to repair it   Troubleshooting | rollup.js Chinese document | rollup.js Chinese website

// rollup.config.js
import babel from 'rollup-plugin-babel'

import babel from 'rollup-plugin-babel'

export default {
  input: './src/index.js', // Entry file
  output: {
    file: './lib/bundle.js', // Export documents
    format: 'cjs' // Output module syntax format
  },
  plugins: [babel()],
  external: ['react'] // Treat [module] as an external dependency
}

  Rerun the package command

$ yarn run rollup -c

  See the warning. Let's simplify the packaging script configuration, package.json:

"scripts": {
    "start": "yarn run rollup -c -w",
    "build": "yarn run rollup -c"
  }

4.4 commissioning

Use npm link local global link package   npm link_ Five tigers war painting halberd - CSDN blog

$ npm link

Install and use this local link package in another project

$ npm link my-first-npm-lib
import React from 'react'
import { Image } from 'my-first-npm-lib'

export default () => {
  return(
    <Image />
  )
}

  Seeing that our components can be displayed and debugged normally, let's write some styles below!

4.5 use   css scope isolation with styled JSX  

styled-jsx - npm You can see the usage of styled JSX   styled-jsx - npm 

$ npm install --save styled-jsx

In Babel   plugins   Medium configuration   styled-jsx/babel

{
  "plugins": [
    "styled-jsx/babel"
  ]
}

Write a little style on our component

import React from 'react'

export default () => {
  return(
    <>
      <h1>Image assembly</h1>
      <style jsx>{`
      h1 {
        color: #1890ff;
      }
    `}</style>
    </>
  )
}

Repackage and refresh the items using the package. You can see the style and changes, and   css scope isolation   

  Then we can normally implement our components? What components? Picture upload preview component!

import React, { useState, useRef } from 'react'

export default () => {
  const [filesUrlList, setFilesUrlList] = useState([])
  const imgRef = useRef({})

  const uploadFile = (e) => {
    const files = e.target.files;
    const setFilesUrl = []
    for (const item of files) {
      setFilesUrl.push(window.URL.createObjectURL(item))
    }
    setFilesUrlList(setFilesUrl)
  }

  return(
    <>
      <input type="file" multiple="multiple" accept="image/*" id='upload-file' onChange={uploadFile} />
      <div>
        {
          filesUrlList.map((item, index) => <img key={index} alt='' ref={imgRef} className='preview-img' src={item} />)
        }
      </div>

      <style jsx>{`
      #upload-file {
        color: #1890ff;
      }
      .preview-img {
        width: 200px;
        height:200px;
        object-fit: contain;
      }
    `}</style>
    </>
  )
}

  5. Release

$ yarn publish

 

  Published successfully, view   npm   Search our bags

 

Published successfully!  

  Welcome to follow, like and comment! ━ (* '∀ *) you!

Topics: node.js Front-end npm rollup