You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:45:03