Create the rollup project

  • First post the address of the final version of the project: rollup-demo
  • Tip: Some of the steps below may seem wrong or imperfect to you, so read on, because they are the building steps I’m exploring step by step
  1. npm init
  • Create a package.json file
  1. NPM I typescript -d Adds typescript
  2. NPM install rollup –save-dev adds rollup
  • Add a file rollup.config.js to the root directory
export default {
  input: "src/main.js".output: {
    file: "bundle.js".format: "es",}};Copy the code
  • Add command to package.json: “build”: “rollup –config”
  1. NPM install eslint –save-dev adds eslint
  2. ./node_modules/.bin/eslint –init Generates an ESLint configuration file
  • Select brower, ESM,typescript
  • Typescript-eslint rule documentation reference
  • Eslint rule documentation reference
  1. Rollup integrates tools such as Babel
  • Rollup integrates with other tools
  • Finally, the test imports the Answer library to determine whether the integration is complete
  • Note the configuration file location of Babel.We place the.babelrc.json file in SRC instead of the project root directory. This allows us to think differently about things like.babelrc.json tests
  1. A rollup installation sass
  • npm install rollup-plugin-sass -D
// rollup.config.js
import sass from "rollup-plugin-sass";
// ...
plugins: [resolve(), sass(), babel({ babelHelpers: "bundled" }), commonjs()];
Copy the code
  • Add postcss autoprefixer
import postcss from "postcss";
import autoprefixer from "autoprefixer";
// ...
plugins: [
  sass({
    output: "bundle.css".insert: true.processor: (css) = >
      postcss([autoprefixer])
        .process(css)
        .then((result) = > result.css),
  }),
];
Copy the code
  • Postcss is a CSS translation tool that can lint CSS, convert future syntax, etc., and can be used with preprocessors such as SCSS
  • Combined with the document
  1. Create a TS file, execute NPM run build error
// Unexpected token (Note that you need plugins to import files that are not JavaScript)
// Static!
Copy the code
  • Install: NPM install@rollup /plugin-typescript –save-devPeer dependencies for rollup
  • In the rollup. Config. Js added
import typescript from "@rollup/plugin-typescript";
// ...
plugins: [
  resolve(),
  sass(),
  typescript(),
  babel({ babelHelpers: "bundled" }),
  commonjs(),
];
Copy the code
  1. Install the run plugin to enable the browser to implement page rendering during the NPM run build
  • npm install –save-dev rollup-plugin-serve
  • When the corresponding port is occupied by another process, it directly reports an error, instead of helping us to occupy the next port. (Source logic like this)
// rollup.config.js
serve({
  open: true.contentBase: "public".host: "localhost".port: 10001});Copy the code
  • Output CSS/JS to public because of path error in packaging
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import babel from "@rollup/plugin-babel";
import sass from "rollup-plugin-sass";
import postcss from "postcss";
import autoprefixer from "autoprefixer";
import typescript from "@rollup/plugin-typescript";
import serve from "rollup-plugin-serve";

export default {
  input: "src/main.js".output: {
    file: "public/bundle.js".name: "test".format: "umd",},plugins: [
    serve({
      open: true.contentBase: "public".host: "localhost".port: 10001,
    }),
    resolve(),
    sass({
      output: "public/bundle.css".insert: true.// Output CSS to the index. HTML head tag
      processor: (css) = >
        postcss([autoprefixer])
          .process(css)
          .then((result) = > result.css),
    }),
    typescript(),
    babel({ babelHelpers: "bundled" }),
    commonjs(),
  ],
};
Copy the code
  • That’s fine, but there’s a problem!
  • Sass uses insert to insert styles into head tags, resulting in a style code in the JS file and a style code in the CSS file, which is redundant

  1. Split into dev and build commands
  • Build: Only CSS and JS files are generatedThe js file does not reference the CSS file. You need to import the CSS file through import
  • Dev: Add a serve configuration to the build configuration and write the index.html file in advance
  • Since there is no way to set process using import/export (only available in node environments), change to the commonJs specification
  • Note that the partial import needs to add curly braces, because there is an export function besides export default
  • Dev is run in public/index.html. If you omit this section, you will not be able to load bundle.css,bundle.js
// rollup.config.js
const { nodeResolve } = require("@rollup/plugin-node-resolve");
const commonjs = require("@rollup/plugin-commonjs");
const { babel } = require("@rollup/plugin-babel");
const sass = require("rollup-plugin-sass");
const postcss = require("postcss");
const autoprefixer = require("autoprefixer");
const typescript = require("@rollup/plugin-typescript");

module.exports = {
  input: "src/main.js".output: {
    file: "dist/bundle.js".name: "bundle".format: "umd".sourcemap: true,},plugins: [
    nodeResolve(),
    sass({
      output: "dist/bundle.css".// insert: true, // Do not insert the head tag, redundant
      processor: (css) = >
        postcss([autoprefixer])
          .process(css)
          .then((result) = > result.css),
    }),
    typescript(),
    babel({ babelHelpers: "bundled".exclude: "**/node_modules/**" }),
    commonjs(),
  ],
};
Copy the code
// rollup.config.dev.js
const serve = require("rollup-plugin-serve");

const config = require("./rollup.config.js");
process.env.NODE_ENV = "development";

const indexPath = "public/index.html";
config.plugins = [
  ...config.plugins,
  serve({
    host: "localhost".port: 3000.onListening: function (server) {
      const address = server.address();
      const host = address.address === "... "" ? "localhost" : address.address;
      // by using a bound function, we can access options as `this`
      const protocol = this.https ? "https" : "http";
      console.log(
        `Server listening at ${protocol}: / /${host}:${address.port}/${indexPath}`); }}),];module.exports = config;
Copy the code
// rollup.config.prod.js
const config = require("./rollup.config.js");
process.env.NODE_ENV = "production";

config.output.sourcemap = false;
config.plugins = [...config.plugins];
module.exports = config;
Copy the code
  1. Compile code obfuscated plugin: rollup-plugin-uglify
  • npm i rollup-plugin-uglify –dev
  • In the rollup. Config. Prod. Js modified
const { uglify } = require("rollup-plugin-uglify");
config.plugins = [...config.plugins, uglify({ sourcemap: false })];
Copy the code
  • Note that rollup-plugin-uglify can only translate ES5 syntax, but the project will use ES6 syntax, so use the recommended Tester instead for translation brevity
const config = require("./rollup.config.js");
const { terser } = require("rollup-plugin-terser");
process.env.NODE_ENV = "production";

config.output.sourcemap = false;
config.plugins = [...config.plugins, terser()];
module.exports = config;
Copy the code
  1. Listen for file changes: rollup-watch
  • I wanted to download it, but after downloading it, I found the same effect as using -w directly. You can see it deprecated on Github translation
  1. Refresh the page in real time (hot update) : rollup-plugin-livereload
  • Hot update principle, look at the source code hot update source
  • reference
  • In the rollup. Config. Dev. Js modified
const livereload = require("rollup-plugin-livereload");
config.plugins = [
  livereload(),
  / / to omit
];
Copy the code
  • But now it can only listen to js file changes and take effect in real time, not SCSS file changes... (Because changing js files will recompile, changing SCSS files will not recompile...)
  • Both Serve and Livereload need to look at the source code again to see how it works and how it can be improved
  1. Add an alias: @rollup/plugin-alias, github.com/rollup/plug…
  • Notice that @ is added, but there is still a yellow underline, warning, at the time of writing. But it worked
import { A } from "@/a.ts";
// Todo will have a warning because @ still has a problem, but it worked successfully...
// There is no way to enter the corresponding file by clicking on it
Copy the code
  • In rollup.config.js add (The solution is to add the SRC alias)
const alias = require("@rollup/plugin-alias");
const customResolver = nodeResolve({
  extensions: [".js".".ts".".json".".scss"]}); alias({entries: [{find: "@".replacement: path.resolve(projectRootDir, ".."."src"),}, {find: "src".replacement: path.resolve(projectRootDir, ".."."src"),
    },
  ],
  customResolver,
});
Copy the code
  1. } rollup-plugin-typescript2 {rollup-plugin-typescript2}} rollup-plugin-typescript2 {rollup-plugin-typescript2}
  • This is a rollup-plugin-typescript rewrite that is slower than the previous version. Let’s see if we can fix the interface error

  • But I found tslib and then looked at rollup-plugin-typescript again and found that the problem was that Tslib was not installed

  • Install tslib, NPM run dev, no error will be reported

  • Problem solved, not using rollup-plugin-typescript for the time being (syntax errors and semantic diagnostics can be printed)

  • But it’s going to compile slower, right? [juejin. Cn/post / 693576…].

    16. Rollup-plugin-prettier (formatting, code prettier)

  • npm install -D prettier rollup-plugin-prettier

  • In the rollup. Config. Js modified

const prettier = require("rollup-plugin-prettier");

prettier({
  printWidth: 100.singleQuote: true.trailingComma: "none".bracketSpacing: true.jsxBracketSameLine: true.tabWidth: 4.arrowParens: "always"});Copy the code
  • Because the prettier part can be a lot of code, modify it by creating a file :.prettierrc.js
const prettierFile = path.resolve(projectRootDir, "..".".prettierrc.js");
plugins: [prettier(prettierFile)];
Copy the code
  1. Add ignore file
  • So let’s first add.eslintignore
dist/**
node_modules/支那Copy the code
  • Add.gitignore. Use the configuration files of other projects directly and delete the useless ones, such as vue.config.js
  1. Adding lint command
  • Add lint to dev,build and package.json
  "scripts": {
    "dev": "npm run lint && rollup -w -c ./config/rollup.config.dev.js"."test": "echo \"Error: no test specified\" && exit 1"."build": "npm run lint && rollup -c ./config/rollup.config.prod.js"."lint": "eslint --fix --ext .ts,.js src"
  }
Copy the code
  1. babel-polyfill
  • Start by using new apis like Map in your code,(Babel only converts new JS syntax by default, such as class and arrow functions)
// main.js
let map = new Map([["a".1],
  ["name".33]]);console.log(map);
// Bundled bundle.js
var map = new Map([["a".1],
  ["name".33]]);console.log(map);
Copy the code
  • You can see that the package is still a Map data structure, and there is no transformation. This is not good! Because IE does not support map data structures
  • Website shows
  • In addition, note that babel-polyfill is only for JS. For CSS, HTML cannot be compatible, so compatibility still needs to be considered, and CSS compatibility depends on PostCSS

  • Note: the Babel website specifically states that after Babel7.4.0, @babel/polyfill will be deprecated and polyfill will be implemented using core-JS and Regenerator-Runtime
  • First installationnpm install core-js regenerator-runtime -D
  • In babelrc. Json configuration
{
  "presets": [["@babel/env",
      {
        "useBuiltIns": "usage".// Load polyfill as needed
        "corejs": {
          "version": 2
        } // Version 3 does not work, default is 2.0
        // [rollup-plugin-prettier] This may take a moment (depends on the size of your bundle)
        / / will be stuck}}]]Copy the code
  • You can see in bundle.js that the package is imported'core-js/modules/es6.map.js'This code provides an es6 API environment
  • Prettier takes longer to format because diff comparison is required before and after the formatting but is still performed after the configuration is modifiedprettier({ cwd: prettierFile, sourcemap: false }); It's no use / /
  • NPM run dev: NPM run dev:Unresolved dependencies
  • This is because we introduced es6.string.iterator.js, web.dom.iterable.js, etc., but didn’t use them (in rollup’s view).
  1. Add a browser compatibility target
  • browserslist
  • Add a.browserslistrc file to the root directory, and tools like Babel /pretitter/postcss automatically get browser compatibility requirements
> 0.25%
> not op_mini all
Copy the code
  • useNPX browserslist Queries the browser version supported by the current project
  1. Change the name of the packaged file
  • First change the entry file to index.ts; The output name is Demo; Index. ts code is:
import Table from "./components/demo/Demo";
import "./assets/styles/index.scss";
const demo = new Demo().render;

export default demo;
Copy the code
  • Change rollup.config.js output to the following
output: {
        file: 'dist/Demo.js',
        name: 'demo', // Output module name, global." XXX "= factory()
        format: 'umd',
        banner: banner, // The packaged header prompt
        sourcemap: true
    }
Copy the code
  1. Generate a. D. ts declaration file
  • Because @rollup/plugin-typescript cannot generate a declaration file, use rollup-plugin-typest2 as prompted
  • Installation:

npm i rollup-plugin-typescript2 -D

  • Modify the rollup. Config. Js
const typescript2 = require('rollup-plugin-typescript2');
typescript2()
Copy the code
  • To generate the declaration file, you need to add a file tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "src"."paths": {
      "@ / *": [ "src/*"]},"declaration": true."sourceMap": true
  },
  "include": ["src/**/*"]."exclude": ["node_modules"."config"."dist"."public"]}Copy the code
  • Declaration :true Generates a declaration file
  • Note that sourceMap must be true. If it is false, the.map file will still be generated because sourceMap is enabled in rollup.config.js
  • The generated file is incorrect. The mappings result is all commas. Unable to generate the correct map file
  • Website shows
  • You can read Ruan Yifeng’s blog about how Sourcemap works. Take a closer look at mozilla sourcemap source code sourcemap
  1. Resolve typescript file alias invalidation issues
  • This is due to a configuration error in tsconfig.json, which was changed to
  • BaseUrl changed from SRC to. Then the SRC path is modified
{
  "compilerOptions": {
    "baseUrl": "."."paths": {
      "@": [ "src"]."src": ["src"]},"declaration": true."sourceMap": true,},"include": ["src/**/*.ts"."src/*.ts"]."exclude": ["node_modules"."config"."dist"."public"]}Copy the code
  • Then we see that SRC can find the alias, but using @ still generates an error.
  • The final solution is: "@/*": [" SRC /*"], that is, the @/* alias.
  1. Readme. md File beautification
  • First I found a plug-in:readme-md-generator
  • Execute command:npx readme-md-generatorTo customize the output content
  • Because the output is too small, modify package.json to add fields as prompted
"engines": {
    "npm": "> = 6.14.12"."node": "> = 10.24.1"
  }
Copy the code
  • Delete the test command, delete the redundant ads, and replace the dev command
  1. Commit specification
  • Commit Commit comply with commit Emoji

The address of the final version of the project: rollup-demo