如何使用Rollup将CDN引入的外部依赖打包到项目产物中
用Rollup将lit-html等外部依赖打包进产物的操作步骤
第一步:安装lit-html依赖
执行安装命令:npm install lit-html --save第二步:修改源码导入语句
把你代码里的CDN导入替换成本地包导入,同时补充自定义元素的注册逻辑:
// 替换掉原来的 https://cdn.skypack.dev/lit-html 导入 import { html, render } from 'lit-html'; class MyHelloElement extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.render(); } render() { render(this.template, this.shadowRoot, { eventContext: this }); } get template() { return html`<h1>Hello, world</h1>`; } } // 注册自定义元素 customElements.define('my-hello', MyHelloElement);
第三步:安装Rollup必要插件
需要@rollup/plugin-node-resolve插件解析node_modules中的依赖,将外部包代码合并进产物,可选安装@rollup/plugin-terser做代码压缩:npm install @rollup/plugin-node-resolve @rollup/plugin-terser --save-dev第四步:编写Rollup配置文件
在项目根目录新建rollup.config.js,内容如下:
import resolve from '@rollup/plugin-node-resolve'; import terser from '@rollup/plugin-terser'; export default { // 替换为你的实际源码入口路径 input: 'src/index.js', output: { // 产物输出路径 file: 'dist/bundle.js', // 浏览器环境可选用es或者iife格式 format: 'es', sourcemap: true }, plugins: [ // 自动解析node_modules依赖,将lit-html打包进产物 resolve(), // 生产环境开启代码压缩 process.env.NODE_ENV === 'production' && terser() ] };
- 第五步:执行打包
在package.json的scripts中添加打包命令:
{ "scripts": { "build": "rollup -c", "build:prod": "NODE_ENV=production rollup -c" } }
执行npm run build即可得到包含lit-html全量代码的打包产物。
验证方式:打包完成后直接在页面引入dist/bundle.js,不需要额外引入lit-html的CDN资源,自定义元素即可正常运行。
内容的提问来源于stack exchange,提问作者marcus
相关产品推荐
相关产品推荐

