小知识,大挑战!本文正在参与“程序员必备小知识”创作活动
Rollup从0到1上手前端组件库开发 | 起步
项目初始化
起步
-
配置你的代码仓库(gitlab, github,coding....)
-
项目初始化
npm init -y -
安装Rollup
yarn add rollup -D
修改package.json 文件
"scripts": {
"dev": "rollup"
}
创建项目目录
.
├── README.md
├── dist # 存放编译后的文件
├── example # 示例文件
├── package.json
├── src # 源码
│ └── index.js
└── yarn.lock
编写我们的第一个测试文件
vim /src/index.js
console.log("Hello my first rollup demo")
export default {}
增加Rollup配置文件
touch rollup.config.dev.js 测试环境Rollup配置文件
touch rollup.config.prod.js 生产环境Rollup配置文件
编写配置文件
vim rollup.config.dev.js
const path = require('path')
const inputPath = path.resolve(__dirname, "./src/index.js") // 输入路径
const outputPath = path.resolve(__dirname, "./dist/payfun.rollbear.dev.js") // 输出路径
console.log(inputPath)
module.exports = {
input: inputPath,
output: {
file: outputPath, // 输出路径
format: 'umd', // 输出的模块协议 es
name: "payfunRollbear" // 模块名称
}
}
修改Package.json中的脚本命令
"scripts": {
"dev": "rollup -c rollup.config.dev.js"
},
运行命令
yarn dev
查看结果
.
├── README.md
├── dist
│ └── payfun.rollbear.dev.js # 编译文件已生成
├── example
├── package.json
├── rollup.config.dev.js
├── rollup.config.prod.js
├── src
│ └── index.js
└── yarn.lock
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 = typeof globalThis !== 'undefined' ? globalThis : global || self, global.payfunRollbear = factory());
})(this, (function () { 'use strict';
console.log("Hello my first rollup demo");
var index = {};
return index;
}));
测试
创建示例目录 example
mkdir example
创建测试Html文件
touch index.html
vim index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件库测试</title>
<script src="../dist/payfun.rollbear.dev.js"></script>
</head>
<body>
</body>
</html>
浏览器打开查看控制台运行结果
代码运行成功
起步成功!
扩展
mac 生成目录树
brew update-reset
brew install tree
$ tree -a 显示所有文件和目录
$ tree -d 显示所有文件名
$ tree -L n 显示项目的层级。n表示层级数。比如想要显示项目三层结构,可以用tree -l 3
$ tree -I pattern 用于过滤不想要显示的文件或者文件夹。比如你想要过滤项目中的node_modules文件夹,可以使用tree -I "node_modules"
$ tree > README.md 将项目结构输出到README.md这个文件。复制代码
附录A: 参数说明
rollup version 2.38.5
=====================================
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 for AMD 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 use in 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 <text> 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 <text> 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 <number> 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 <files> Exclude files from being watched
--watch.include <files> 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.org