Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

Rollup from 0 to 1 to fit the front-end component library development | started

Project initialization

start

  • Configure your repository (Gitlab, Github,coding….)

  • The project initializes NPM init-y

  • Install Rollup yarn add Rollup -d

Modify the package.json file

"scripts": {
    "dev": "rollup"
}
Copy the code

Create a project directory

.Heavy Exercises ── Heavy Exercises. Md heavy Exercises ─ dist# Save the compiled file├ ─ ─ example# sample file├ ─ ─ package. Json ├ ─ ─ the SRC# source│ ├ ─ ├ ─ sci-1.txt ├ ─ sci-1.txtCopy the code

Write our first test file

vim /src/index.js

console.log("Hello my first rollup demo")
export default {}
Copy the code

Add the Rollup configuration file

Touch rollup.config.dev.js Test environment rollup configuration file

Touch rollup.config.prod.js Production environment rollup configuration file

Writing configuration files

vim rollup.config.dev.js

const path = require('path')

const inputPath = path.resolve(__dirname, "./src/index.js") // Input path
const outputPath = path.resolve(__dirname, "./dist/payfun.rollbear.dev.js") // Output path
console.log(inputPath)
module.exports = {
    input: inputPath,
    output: {
        file: outputPath, // Output path
        format: 'umd'.// The output module protocol es
        name: "payfunRollbear" // Module name}}Copy the code

Modify script commands in package. json

"scripts": {
    "dev": "rollup -c rollup.config.dev.js"
},
Copy the code

Run the command

yarn dev

View the results

.├ ── Heavy Exercises, exercises, exercises, exercises, exercises, exercisesThe compile file has been generated├ ─ ─ example ├ ─ ─ package. Json ├ ─ ─ a rollup. Config. Dev. Js ├ ─ ─ a rollup. Config. Prod. Js ├ ─ ─ the SRC │ └ ─ ─ index. The js └ ─ ─ yarn. The lockCopy the code

cat /dist/payfun.rollbear.dev.js

(function (global, factory) {
	typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory() :
	typeof define === 'function' && define.amd ? define(factory) :
	(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.payfunRollbear = factory()); }) (this, (function () { 'use strict';

	console.log("Hello my first rollup demo");

	var index = {};

	return index;

}));
Copy the code

test

Create the example directory example

mkdir example

Create the test Html file

touch index.html

vim index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Component library testing</title>
    <script src=".. /dist/payfun.rollbear.dev.js"></script>
</head>
<body>

</body>
</html>

Copy the code

The browser opens to view the console running result

Code running successfully

Successful start!

extension

MAC generates a directory tree

brew update-reset

brew install tree

$tree -a displays all files and directories $tree -d displays all file names $tree -l n Displays the hierarchy of the project. N indicates the number of tiers. For example, if you want to display the three-tier structure of the project, you can use tree-L 3 $tree-I pattern to filter files or folders that you do not want to display. For example, if you want to filter the node_modules folder in your project, use tree-i"node_modules"$tree > readme. md Prints the project structure to the readme. md file. Copy the codeCopy the code

Appendix A: Parameter description

A rollup version 2.38.5 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = the Usage: rollup [options] < entry file > Basic options: -c, --config <filename> Use this config file (if argument is used but value
                              is unspecified, defaults to rollup.config.js)
-d, --dir <dirname>         Directory for chunks (if absent, prints to stdout)
-e, --external <ids>        Comma-separate list of module IDs to exclude
-f, --format <format>       Type of output (amd, cjs, es, iife, umd, system)
-g, --globals <pairs>       Comma-separate list of `moduleID:Global` pairs
-h, --help                  Show this help message
-i, --input <filename>      Input (alternative to <entry file>)
-m, --sourcemap             Generate sourcemap (`-m inline` for inline map)
-n, --name <name>           Name for UMD export
-o, --file <output>         Single output file (if absent, prints to stdout)
-p, --plugin <plugin>       Use the plugin specified (may be repeated)
-v, --version               Show version number
-w, --watch                 Watch files in bundle and rebuild on changes
--amd.id <id>               ID forAMD module (default is anonymous) --amd.autoId Generate the AMD ID based off the chunk name --amd.basePath <prefix> Path  to prepend to auto generated AMD ID --amd.define <name> Function to usein place of `define`
--assetFileNames <pattern>  Name pattern for emitted assets
--banner <text>             Code to insert at top of bundle (outside wrapper)
--chunkFileNames <pattern>  Name pattern for emitted secondary chunks
--compact                   Minify wrapper code
--context <variable>        Specify top-level `this` value
--entryFileNames <pattern>  Name pattern for emitted entry chunks
--environment <values>      Settings passed to config file (see example)
--no-esModule               Do not add __esModule property
--exports <mode>            Specify export mode (auto, default, named, none)
--extend                    Extend global variable defined by --name
--no-externalLiveBindings   Do not generate code to support live bindings
--failAfterWarnings         Exit with an error if the build produced warnings
--footer <text>             Code to insert at end of bundle (outside wrapper)
--no-freeze                 Do not freeze namespace objects
--no-hoistTransitiveImports Do not hoist transitive imports into entry chunks
--no-indent                 Don't indent result --no-interop Do not include interop block --inlineDynamicImports Create single bundle when using dynamic imports --intro 
      
        Code to insert at top of bundle (inside wrapper) --minifyInternalExports Force or disable  minification of internal exports --namespaceToStringTag Create proper `.toString` methods for namespaces --noConflict Generate a noConflict method for UMD globals --outro 
       
         Code to insert at end of bundle (inside wrapper) --preferConst Use `const` instead of `var` for exports --no-preserveEntrySignatures Avoid facade chunks for entry points  --preserveModules Preserve module structure --preserveModulesRoot Put preserved modules under this path at root level --preserveSymlinks Do not follow symlinks when resolving files --shimMissingExports Create shim variables for missing exports --silent Don'
       
      t print warnings
--sourcemapExcludeSources   Do not include source code in source maps
--sourcemapFile <file>      Specify bundle position for source maps
--stdin=ext                 Specify file extension used for stdin input
--no-stdin                  Do not read "-" from stdin
--no-strict                 Don't emit `"use strict"; ` in the generated modules --strictDeprecations Throw errors for deprecated features --systemNullSetters Replace empty SystemJS setters with `null` --no-treeshake Disable tree-shaking optimisations --no-treeshake.annotations Ignore pure call annotations --no-treeshake.moduleSideEffects Assume modules have no side-effects --no-treeshake.propertyReadSideEffects Ignore property access side-effects --no-treeshake.tryCatchDeoptimization Do not turn off try-catch-tree-shaking --no-treeshake.unknownGlobalSideEffects Assume unknown globals do not throw --waitForBundleInput Wait for bundle input files --watch.buildDelay 
      
        Throttle watch rebuilds --no-watch.clearScreen Do not clear the screen when rebuilding --watch.skipWrite Do not write files to disk when watching --watch.exclude 
       
         Exclude files from being watched --watch.include 
        
          Limit watching to specified files Examples: # use settings in config file rollup -c # in config file, process.env.INCLUDE_DEPS === '
        
       
      true'
# and process.env.BUILD === 'production' rollup -c --environment INCLUDE_DEPS,BUILD:production # create CommonJS bundle.js from src/main.js rollup --format=cjs  --file=bundle.js -- src/main.js # create self-executing IIFE using `window.jQuery` # and `window._` as external globals  rollup -f iife --globals jquery:jQuery,lodash:_ \ -i src/app.js -o build/app.js -m build/app.js.map Notes: * When piping to stdout, only inline sourcemaps are permitted For more information visit https://rollupjs.orgCopy the code