-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
rollup 打包实践 #6
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rollup 打包实践
原文链接
简介
rollup
是一款像webpack
一样的JS代码打包工具。它特别适合类库的维护,有了它你可以把单个复杂庞大的类库拆分成多个文件模块编写,最终打包成符合UMD
、AMD
、ESM
等格式的单个或多个文件。它可以利用最新的ES6+modules
规范,Tree-Shaking
不需要的代码,这样你就可以放心的引入你喜欢类库中的某个方法,而不必担心引入整个类库。Vue 官方使用
JS 模块化演进
著名的AMD两种实现,现在很少看见用了
优势:
Tree-Shaking
你有遇到一下问题吗?
...
如果你有以上困惑,rollup 统统能满足你。
构建你的第一个包
新建src/main.js
新建src/foo.js
命令行打包
CommonJS
规范, 输出dist/bundle.jsdist/bundle.js:
命令行太长手敲太烦?使用配置文件!
在项目根目录下新建 rollup.config.js
现在只需要输入以下命令即可达到以上效果
结合 npm 使用 rollup
初始化 package.json
不全局安装,避免全局安装版本不统一,npx 使用 rollup
// 在package.json 中添加
常见插件使用
src/main.js 修改如下
解析 json 文件需要引入 rollup-plugin-json 包
rollup.config.js 修改如下
最终打包dist/bundle.js,多余的无用json字段被祛除了
修改 src/main.js 如下
安装依赖测试包 the-answer
最终打包结果,the-answer 没有打进bundle.js,在node环境可用。
命令行窗口出现警告
CommonJS包需要 rollup-plugin-node-resolve 插件
修改 rollup.config.js
打包结果,发现 the-answer 被打进去了
安装 rollup-plugin-babel
rollup.config.js 修改如下
新建babel配置文件 src/.babelrc
安装babel核心包:
@babel/core
,@babel/preset-env
在 src/main.js 中使用 ES6 的箭头函数
打包结果
安装 rollup-plugin-uglify
修改 rollup.config.js 如下
rollup 内置支持,但默认关闭
例如根据主入口文件 src/index.js 生成 UMD、ESM 规范的包文件
注意: uglify 不支持 es6,用
rollup-plugin-terser
官方推荐插件
建议最好都打个ESM包并在
package.json
指明,如 Vue。这样做的好处是便于webpack、rollup 利用最新特性
Tree-Shaking
静态解析代码,让你的包更小。也让大家能更好的向es6+规范过渡。
更多特性请移步官方文档
The text was updated successfully, but these errors were encountered: