The project structure

├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt// Project source code└ ─ ─ the components// Component directory├ ─ ─ button │ ├ ─ ─ index. The js │ └ ─ ─ style.css. CSS ├ ─ ─ the hello │ ├ ─ ─ index. The js │ └ ─ ─ style.css. CSS └ ─ ─ index, jsCopy the code

Implementation component

1. Install dependencies

npm install react react-dom
Copy the code

2. Write the Button component

// src/components/button/index.js
import * as React from "react";
import "./style.css";

const Button = (props) = > {
  const handleClick = () = > {
    props.onClick && props.onClick();
  };

  return (
    <button className="pp-button" onClick={handleClick}>
      {props.children}
    </button>
  );
};

export default Button;

// src/components/button/style.css
.pp-button {
  border: none;
  padding: 10px 15px;
  font-size: 14px;
}
Copy the code

Write the Hello component

// src/components/hello/index.js
import * as React from "react";
import "./style.css";

const Hello = (props) = > {
  return (
    <div className="pp-hello">
      hello <span className="pp-name">{props.name}</span>
    </div>
  );
};

export default Hello;

// src/components/hello/style.css
.pp-hello {
  font-size: 16px;
}
.pp-hello .pp-name {
  color: red;
}

Copy the code

4. Export components

// src/components/index.js

export { default as Button } from "./button";
export { default as Hello } from "./hello";

Copy the code

Use Parcel to run the project

1. Install dependencies

npm install parcel-bundler --save-dev

npm install @babel/preset-react --save-dev
Copy the code

Create the.babelrc file

{
  "presets": ["@babel/preset-react"]}Copy the code

3. Create an entry file

// src/index.html
<html>
  <body>
    <div id="root"></div>
    <script src="./index.js"></script>
  </body>
</html>


// src/index.js
import React from "react";
import ReactDOM from "react-dom";

import { Button, Hello } from "./components";

const App = () = > {
  return (
    <>
      <section>
        <Button onClick={()= > alert('click')}>click me</Button>
      </section>
      <section>
        <Hello name="jack" />
      </section>
    </>
  );
};

ReactDOM.render(<App />.document.getElementById("root"));

Copy the code

4. Update package.json

"scripts": {
   "dev": "parcel src/index.html",},Copy the code

5. Run projects

npm run dev
Copy the code

Package projects using rollup

1. Install rollup

npm install rollup --save-dev
Copy the code

2. Install rollup

npm install @rollup/plugin-node-resolve --save-dev

npm install @rollup/plugin-commonjs --save-dev

npm install rollup-plugin-babel --save-dev

npm intall rollup-plugin-postcss --save-dev
Copy the code

A rollup plug-in

Rollup /plugin-node-resolve

@rollup/plugin-node-resolve tells rollup how to find external modules. If third-party modules are imported, they are packaged together.

A warning is generated when @rollup/plugin-node-resolve is not usedReact was not included in the files we packed.

Using the @rollup/plugin-node-resolve configuration:

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [resolve()]
};
Copy the code

2, @ rollup/plugin – commonjs

Rollup /plugin-commonjs converts commonJS to ES2015.

Some libraries expose ES modules, which you can import as is. But for now, most packages on NPM are exposed as CommonJS modules. Before we do that, we need to convert CommonJS to ES2015 before Rollup can process them.

The @rollup/ plugin-commonJS plug-in does just that.

Note that most of the time @rollup/ plugin-Commonjs should be used before other plug-ins convert modules — this is to prevent other plug-ins from making changes that break CommonJS detection. One exception to this rule is the Babel plugin, if you are using it, put it before CommonJS.

Error packaging is reported when @rollup/plugin-commonjs is not used

With @rollup/plugin-commonjs configuration:

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from "@rollup/plugin-commonjs";

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [
   	commonjs(),
   	resolve()
  ]
};
Copy the code

3, a rollup – plugin – postcss

Rollup-plugin – PostCSS, seamless integration of rollup and PostCSS.

Rollup-plugin-postcss is not used, packaging will report an errorRollup-plugin-postcss configuration:

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from "@rollup/plugin-commonjs";
import postcss from 'rollup-plugin-postcss';

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [
   	commonjs(),
    resolve(),
    postcss()
  ]
};
Copy the code

4, a rollup – plugin – Babel

Rollup-plugin-babel, seamless integration of rollup with Babel.

Rollup-plugin-babel is not used, packaging will report an errorRollup-plugin-babel configuration:

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from "@rollup/plugin-commonjs";
import postcss from 'rollup-plugin-postcss';
import babel from "rollup-plugin-babel";

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [
  	babel({
      exclude: "node_modules/**",
      presets: ["@babel/preset-react"],
    }),
   	commonjs(),
    resolve(),
    postcss()
  ]
};
Copy the code

Rollup configuration file

rollup.config.js

import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import postcss from 'rollup-plugin-postcss';
import babel from "rollup-plugin-babel";

export default {
  input: "./src/components/index.js", 
  output: [
    {
      format: "cjs",
      dir: "cjs",
      name: "index.js",
    },
    {
      format: "es",
      exports: "named",
      dir: "es",
      name: "index.js",
    },
  ],
  plugins: [
    babel({
      exclude: "node_modules/**",
      presets: ["@babel/preset-react"],
    }),
    commonjs(),
    resolve(),
    postcss()
  ],
};
Copy the code

Output Core parameter:

// required (can be an array, for multiple outputs)
output: {
    // core output options
    dir,
    file,
    format, // required
    globals,
    name,
    plugins,
 }
Copy the code

Package by component

rollup.config.js

import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import postcss from "rollup-plugin-postcss";
import babel from "rollup-plugin-babel";
import path from "path";
import fs from "fs-extra";

const plugins = [
  babel({
    exclude: "node_modules/**",
    presets: ["@babel/preset-react"], }), commonjs(), resolve(), postcss(), ]; Const getComponents = async () => {const componentsPath = path.join(__dirName,"src/components"); Const files = await fs.readdir(componentsPath); const files = await fs.readdir(componentsPath); // console.log(files); / / /'button'.'hello'.'index.js'] const components = await promise.all (files.map(async (name) => {// const comPath = path.join(componentsPath, name); // Component entry file const entry = path.join(comPath,"index.js"); // Get the current file information conststat= await fs.stat(comPath); // Not a directory, return directlyif(! stat.isDirectory()) {returnnull; } const hasFile = await fs.pathexists (entry);if(! hasFile) {return null;
      }
      const result = { name, url: entry };
      // console.log(result);
      // {
      //   name: 'button',
      //   url: '/pp-ui/src/components/button/index.js'
      // }
      returnresult; }));return components;
};

exportDefault async () => {// delete package directory await fs.remove(path.join(__dirname,"es"));
  await fs.remove(path.join(__dirname, "cjs"));
  await fs.remove(path.join(__dirname, "dist")); Const Components = await getComponents(); Const componentList = component.filter ((comp) => comp).map(({name, url}) => ({input: {[name]: const componentList = component.filter ((comp) => comp).map(({input: {[name]) : url }, output: [ { format:"cjs",
          dir: "cjs",
          entryFileNames: "[name]/index.js",
          exports: "named",
        },
        {
          format: "es",
          dir: "es",
          entryFileNames: "[name]/index.js",
          exports: "named", }, ], plugins, })); Const componetIndex = {input:"./src/components/index.js",
    output: [
      {
        format: "cjs",
        dir: "cjs",
        name: "index.js",
      },
      {
        format: "es",
        dir: "es",
        name: "index.js",
      },
    ],
    plugins,
  };

  return [...componentList, componetIndex];
};

Copy the code

Public dependencies are not packaged

const external = (id) => /^react|react-dom|classnames/.test(id);

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [],
  // indicate which modules should be treated as external
  external
};
Copy the code

Update package. Json

"peerDependencies": {
  "classnames": "^ 2.3.1." "."react": "^ 17.0.2"."react-dom": "^ 17.0.2"
},
Copy the code

Packaging by environment

1. Install cross-env

npm install --save-dev cross-env
Copy the code

2, production environment compression code

npm install rollup-plugin-terser --save-dev
Copy the code

3. Update package.json

"scripts": {
    "build": "npm run build:prod"."build:dev": "cross-env BUILD_ENV=development rollup -c"."build:prod": "cross-env BUILD_ENV=production rollup -c"
 },
Copy the code

4. Update rollup.config.js

import { terser } from 'rollup-plugin-terser';

const isProd = process.env.BUILD_ENV === 'production';

export default {
  input: 'src/main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [
  	isProd ? terser() : null
  ],
};
Copy the code

Extracting CSS files

import postcss from "rollup-plugin-postcss";

const isProd = process.env.BUILD_ENV === "production";

export default {
  input: "src/main.js",
  output: {
    file: "bundle.js",
    format: "cjs",
  },
  plugins: [
    isProd
      ? postcss({
          extract: true,
          minimize: true,
        })
      : postcss(),
  ],
};
Copy the code

Configuration package. Json

1. Configure the import file

{
	"main": "dist/index.js"."module": "es/index.js",}Copy the code

The pkg.main field points to the CommonJS module; The pkg.module field points to the ES6 module;

2. Release file configuration (Files)

The files field describes the list of files that we push to the NPM server after using the NPM publish command. If you specify a folder, the contents of the folder will be included

{
	 "files": [
    "/dist"."/es"]}Copy the code

Talk about package. The json file zhuanlan.zhihu.com/p/34164963 module in the field

The Module field in package.json is github.com/sunyongjian…

Package. The explanation zhuanlan.zhihu.com/p/148089474 json file

Release NPM

1. Register with www.npmjs.com/signup

2. Go to the project directory and executenpm login, enter the user name and password;The following output is displayed after successful login:

Logged in as pengjielee on https://registry.npmjs.org/
Copy the code

3. Execute NPM publish

NPM common publishing error

1. The package name already existsBefore publishing, you can look it upwww.npmjs.com/Let’s see if there is

2. The registered email address is not verified