# @11ty/eleventy-plugin-bundle 中文文档

规范地址：https://npmcn.com/package/%4011ty/eleventy-plugin-bundle/

版本：4\.0\.3
npm 元数据更新时间：2026-09-17T22:15:51.776Z
中文译文更新时间：2026-11-05T17:18:06.903Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%4011ty/eleventy-plugin-bundle
原文对照：https://npmcn.com/package/%4011ty/eleventy-plugin-bundle/?lang=original
项目主页：https://www.11ty.dev/
源码仓库：https://github.com/11ty/eleventy-plugin-bundle

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：40.8 kB，10 个文件
- 模块格式：ES Module
- TypeScript 类型：未声明
- Node.js 要求：\>=22
- 运行依赖：3 个
- 首次发布：2023-02-02T21:47:47.519Z
- 最新版本发布：2026-09-17T22:15:51.422Z
- 近 30 天下载量：701290（2026-10-04 至 2026-11-02，npm 官方下载统计）
- 已发布版本数：23（近 12 个月 4 个）

## 中文简介

小捆子代码,小捆子快乐.

## 安装

```sh
npm install @11ty/eleventy-plugin-bundle
```

也可以使用：`pnpm add @11ty/eleventy-plugin-bundle`、`yarn add @11ty/eleventy-plugin-bundle`、`bun add @11ty/eleventy-plugin-bundle`

## README

# 十一号插座

小捆子代码,小捆子快乐.

创建最小的每页或应用程序级捆绑 CSS, JavaScript, 或 HTML 以包含在您的"十一" 项目中 .

使其易于执行关键CSS,只使用中的CSS/JS捆绑,SVG图标库,或通过XHR加载的次级HTML内容.

## 为什么?

这个项目是11T的最小可行捆绑和资产管道. 它不执行任何转录或代码操作(默认). 你输入的代码是出局的代码(可配置) `transforms` 若您想修改代码.

对于更大,更复杂的使用案例,你可能想要使用一个更完整的功能捆绑器,比如Vite,Parcel,Webpack,滚出,Esbuilt,或者其他.

但请注意,一个全能的捆绑机的构建性能成本相当高,所以要注意权衡使用这种捆绑机风格的成本与这个插件是否具有足够的功能供您使用,特别是当平台成熟时,我们看到代码转录(ES模块随处可见)的回报率不断下降.

## 安装

无需安装。 从"十一"核心开始 `v3.0.0` 而更新,这个插件现在与"十一"捆绑在一起.

## 使用量

默认情况下, Bundle 插件 v2.0 不包括任何默认捆绑 。 你必须自己通过 `eleventyConfig.addBundle`。 。 。 .

> \[注\] 使用 WebC 十一进取插件时会出现一个显著的例外 `css`, (中文(简体) ), `js`,以及 `html` 包裹给你.

要创建捆绑类型, 请使用 `eleventyConfig.addBundle` 在您的"十一"配置文件中(默认) `eleventy.config.js`:

```js
// eleventy.config.js
export default function(eleventyConfig) {
    eleventyConfig.addBundle("css");
};
```

这有两件事:

1.  创建新 `css` 在此捆绑中添加任意代码的短码
2.  添加数 `"css"` 作为符合条件的类型参数 `getBundle` 财务报告和审定财务报表 `getBundleFileUrl` 简码.

### 完整选项列表

```js
export default function(eleventyConfig) {
    eleventyConfig.addBundle("css", {
        // (Optional) Folder (relative to output directory) files will write to
        toFileDirectory: "bundle",

        // (Optional) File extension used for bundle file output, defaults to bundle name
        outputFileExtension: "css",

        // (Optional) Name of shortcode for use in templates, defaults to bundle name
        shortcodeName: "css",
        // shortcodeName: false, // disable this feature.

        // (Optional) Modify bundle content
        transforms: [],

        // (Optional) If two identical code blocks exist in non-default buckets, they’ll be hoisted to the first bucket in common.
        hoist: true,

        // (Optional) In 11ty.js templates, having a named export of `bundle` will populate your bundles.
        bundleExportKey: "bundle",
        // bundleExportKey: false, // disable this feature.
    });
};
```

更多信息 [`hoist` 并重复捆绑起](https://github.com/11ty/eleventy-plugin-bundle/issues/5)。 。 。 .

### 通用短码

以下通用短码(参见: `njk`, (中文(简体) ), `liquid`, (中文(简体) ), `hbs`, (中文(简体) ), `11ty.js`,以及 `webc`)由此插件提供:

-   `getBundle` 作为字符串检索捆绑的代码.
-   `getBundleFileUrl` 创建磁盘上的捆绑文件,并将 URL 检索到该文件.

这里有一个 [现实世界承诺在 `eleventy-base-blog` 项目](https://github.com/11ty/eleventy-base-blog/commit/c9595d8f42752fa72c66991c71f281ea960840c9?diff=split)。 。 。 .

### 示例: 在 11ty 的 Markdown 文件中添加捆绑代码

```md
# My Blog Post

This is some content, I am writing markup.

{% css %}
em { font-style: italic; }
{% endcss %}

## More Markdown

{% css %}
strong { font-weight: bold; }
{% endcss %}
```

修改为:

```html
<h1>My Blog Post</h1>

<p>This is some content, I am writing markup.</p>

<h2>More Markdown</h2>
```

注意,捆绑的代码被排除了!

_有几个 [更多实例](https://npmcn.com/package/%4011ty/eleventy-plugin-bundle/#readme-examples)来啊!_

### 捆绑代码

```html
<!-- Use this *anywhere*: a layout file, content template, etc -->
<style>{% getBundle "css" %}</style>

<!--
You can add more code to the bundle after calling
getBundle and it will be included.
-->
{% css %}* { color: orange; }{% endcss %}
```

### 将捆绑写入文件

将捆绑的内容写入输出目录中的内容包文件位置, 并将 URL 返回到文件中, 这样使用 :

```html
<link rel="stylesheet" href="{% getBundleFileUrl "css" %}">
```

> **注:** 将捆绑写入文件对于首次访问的空卡很可能会比较慢,但在浏览器中缓存的重复视图(并跨多页,也更好).

### 资产桶

```html
<!-- This goes into a `defer` bucket (the bucket can be any string value) -->
{% css "defer" %}em { font-style: italic; }{% endcss %}
```

```html
<!-- Pass the arbitrary `defer` bucket name as an additional argument -->
<style>{% getBundle "css", "defer" %}</style>
<link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
```

A 类 `default` 桶隐含:

```html
<!-- These two statements are the same -->
{% css %}em { font-style: italic; }{% endcss %}
{% css "default" %}em { font-style: italic; }{% endcss %}

<!-- These two are the same too -->
<style>{% getBundle "css" %}</style>
<style>{% getBundle "css", "default" %}</style>
```

### 实例

#### 关键支助

```js
// eleventy.config.js
export default function(eleventyConfig) {
    eleventyConfig.addBundle("css");
};
```

使用资产桶将 CSS 分隔为 `default` 桶和一个 `defer` 水桶 同步装入.

_(注意一些HTML锅炉板被从以下样本中省去)_

```html
<!-- … -->
<head>
    <!-- Inlined critical styles -->
    <style>{% getBundle "css" %}</style>

    <!-- Deferred non-critical styles -->
    <link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}" media="print" onload="this.media='all'">
    <noscript>
        <link rel="stylesheet" href="{% getBundleFileUrl 'css', 'defer' %}">
    </noscript>
</head>
<body>
    <!-- This goes into a `default` bucket -->
    {% css %}/* Inline in the head, great with @font-face! */{% endcss %}
    <!-- This goes into a `defer` bucket (the bucket can be any string value) -->
    {% css "defer" %}/* Load me later */{% endcss %}
</body>
<!-- … -->
```

**相关**数字 :

-   看看这个 [使用"十一边"演示关键 CSS](https://demo-eleventy-edge.netlify.app/critical-css/) 用于不使用 JavaScript 的重复视图优化.
-   您可能想用 [`fetchpriority`](https://www.smashingmagazine.com/2022/04/boost-resource-loading-new-priority-hint-fetchpriority/) 何时 [浏览器支持改进](https://caniuse.com/mdn-html_elements_link_fetchpriority)。 。 。 .

#### SVG 图标库

这里 `svg` 正在创建捆绑.

```js
// eleventy.config.js
export default function(eleventyConfig) {
    eleventyConfig.addBundle("svg");
};
```

```html
<svg width="0" height="0" aria-hidden="true" style="position: absolute;">
    <defs>{% getBundle "svg" %}</defs>
</svg>

<!-- And anywhere on your page you can add icons to the set -->
{% svg %}
<g id="icon-close"><path d="…" /></g>
{% endsvg %}

And now you can use `icon-close` in as many SVG instances as you’d like (without repeating the heftier SVG content).

<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
<svg><use xlink:href="#icon-close"></use></svg>
```

#### 反应后盔型 `<head>` 添加数

```js
// eleventy.config.js
export default function(eleventyConfig) {
    eleventyConfig.addBundle("html");
};
```

这可能存在于一个"十一"布局文件中 :

```html
<head>
    {% getBundle "html", "head" %}
</head>
```

然后在内容中,你可能会想 特定页面 `preconnect`数字 :

```html
{% html "head" %}
<link href="https://v1.opengraph.11ty.dev" rel="preconnect" crossorigin>
{% endhtml %}
```

#### 装有 Render 插件的套装

您可以在 `{% css %}` 如果您想使用"十一"模板类型做更多的高级工作, 也会使用简码.

这个例子假设您添加了 [渲染插件](https://www.11ty.dev/docs/plugins/render/) 编辑 [`scss` 自定义模板类型](https://www.11ty.dev/docs/languages/custom/) 到您的十一配置文件.

```html
{% css %}
  {% renderTemplate "scss" %}
  h1 { .test { color: red; } }
  {% endrenderTemplate %}
{% endcss %}
```

现在编译的 Sass 在您的默认捆绑中可以使用, 并将出现在 `getBundle` 财务报告和审定财务报表 `getBundleFileUrl`。 。 。 .

#### 使用方式 [网络C](https://www.11ty.dev/docs/languages/webc/)

从开始 `@11ty/eleventy-plugin-webc@0.9.0` (轨道在 [问题48](https://github.com/11ty/eleventy-plugin-webc/issues/48)) 此插件默认在"十一通" WebC 插件中使用. 具体来说, [WebC Bundler 模式](https://www.11ty.dev/docs/languages/webc/#css-and-js-\(bundler-mode\)) 现在在引擎盖下使用捆绑插件.

要将 CSS 添加到 WebC 的捆绑中, 您需要使用 `<style>` 网页或组件中的元素 :

```html
<style>/* This is bundled. */</style>
<style webc:keep>/* Do not bundle me—leave as is */</style>
```

要在WebC的一行页面中添加JS,您需要 `<script>` 网页或组件中的元素 :

```html
<script>/* This is bundled. */</script>
<script webc:keep>/* Do not bundle me—leave as is */</script>
```

-   通过 WebC 帮助者的现有呼叫 `getCss` 或者说 `getJs` (例如:. `<style @raw="getCss(page.url)">`) 已被监听到 `getBundle` (计: `"css"` 财务报告和审定财务报表 `"js"` (分别为)自动.
    -   为了保持一致性,您可能倾向于在任何地方使用捆绑插件方法名称: `<style @raw="getBundle('css')">` 财务报告和审定财务报表 `<script @raw="getBundle('js')">` 两者都很好.
-   在 WebC 之外, 通用过滤器 `webcGetCss` 财务报告和审定财务报表 `webcGetJs` 十一岁被撤走 `v3.0.0-alpha.10` 赞成: `getBundle` 通用短码( N)`{% getBundle "css" %}` 财务报告和审定财务报表 `{% getBundle "js" %}` 页:1.

#### 修改捆绑输出

你可以用电线连接到自己的 方便的自动调用器来转换捆绑输出 以下是一个简单的例子: [`postcss` 融合](https://github.com/postcss/postcss#js-api)。 。 。 .

```js
const postcss = require("postcss");
const postcssNested = require("postcss-nested");

export default function(eleventyConfig) {
    eleventyConfig.addBundle("css", {
        transforms: [
            async function(content) {
                // this.type returns the bundle name.
                // Same as Eleventy transforms, this.page is available here.
                let result = await postcss([postcssNested]).process(content, { from: this.page.inputPath, to: null });
                return result.css;
            }
        ]
    });
};
```

## 高级

### 限制

Bundles 不支持筑巢或再生( yet?) 。 如果这对你们有用,请提出一个问题!

## 常见问题

### @11ty/eleventy-plugin-bundle 是什么？

小捆子代码,小捆子快乐\.

### 如何安装 @11ty/eleventy-plugin-bundle？

在项目目录运行 npm install @11ty/eleventy-plugin-bundle，或使用 pnpm add / yarn add / bun add。

### @11ty/eleventy-plugin-bundle 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/11ty\_\_eleventy-plugin-bundle 是否存在。

### @11ty/eleventy-plugin-bundle 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @11ty/eleventy-plugin-bundle 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @11ty/eleventy-plugin-bundle 可以商用吗？

@11ty/eleventy-plugin-bundle 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @11ty/eleventy-plugin-bundle 的下载量有多少？

根据 npm 官方下载统计，@11ty/eleventy-plugin-bundle 在 2026/10/04 – 2026/11/02 这 30 天内被下载 701,290 次，日均约 23,376 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @11ty/eleventy-plugin-bundle 还在维护吗？

最新版本 4\.0\.3 发布于 2026/09/18（1 个月前）；至今共发布 23 个版本，其中过去 12 个月发布了 4 个；首次发布于 2023/02/03。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

