# @enhance/ssr 中文文档

规范地址：https://npmcn.com/package/%40enhance/ssr/

版本：4\.0\.3
npm 元数据更新时间：2024-07-22T19:03:45.324Z
中文译文更新时间：2026-11-13T19:01:12.452Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40enhance/ssr
原文对照：https://npmcn.com/package/%40enhance/ssr/?lang=original

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

- 包体积（解压后）：53.3 kB，43 个文件
- 模块格式：ES Module
- TypeScript 类型：未声明
- Node.js 要求：\>=14\.0\.0
- 运行依赖：2 个
- 首次发布：2021-12-10T23:52:06.976Z
- 最新版本发布：2024-07-22T19:03:45.017Z
- 近 30 天下载量：3135（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：47（近 12 个月 0 个）

## 中文简介

对有模板和槽支持的自定义元素进行服务器侧渲染

## 安装

```sh
npm install @enhance/ssr
```

也可以使用：`pnpm add @enhance/ssr`、`yarn add @enhance/ssr`、`bun add @enhance/ssr`

## README

# 加强安全部门改革

服务器侧渲染 [自定义元素](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements)。 。 。 .

通过支持自定义元素和 [语法](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots#adding_flexibility_with_slots)。 。 。 .

## 安装

`npm i @enhance/ssr`

## 使用量

```javascript
import HelloWorld from './path/to/elements/hello-world.mjs'
import enhance from '@enhance/ssr'
const html = enhance({
  elements: {
    'hello-world': HelloWorld
  }
})
console.log(html`<hello-world greeting="Well hi!"></hello-world>`)
```

### 用于服务器侧面渲染的自定义元素模板

元素是传递的纯函数,该函数包含 `html` 函数用于扩展自定义元素和由 `attrs` 是自定义元素上设置的属性和 a `store` 包含应用程序状态的对象.

```javascript
export default function HelloWorld({ html, state }) {
  const { attrs } = state
  const { greeting='Hello World' } = attrs
  return html`
    <style scope="global">
      h1 {
        color: red;
      }
    </style>

    <h1>${greeting}</h1>
  `
}
```

输出

```javascript
<head>
  <style scope="global">
    h1 {
      color: red;
    }
  </style>
</head>

<body>
<hello-world>
  <h1>Hello World</h1>
</hello-world>
</body>
```

### 渲染函数

您也可以使用显示对象 `render` 函数作为模板。 渲染函数会通过相同的参数 `{ html:function, state:object }`。 。 。 .

```javascript
{
  attrs: [ 'label' ],
  init(el) {
    el.addEventListener('click', el.click)
  },
  render({ html, state }) {
    const { attrs={} } = state
    const { label='Nope' } = attrs
    return html`
    <pre>
      ${JSON.stringify(state)}
    </pre>
    <button>${ label }</button>
    `
  },
  click(e) {
    console.log('CLICKED')
  },
  adopted() {
    console.log('ADOPTED')
  },
  connected() {
    console.log('CONNECTED')
  },
  disconnected() {
    console.log('DISCONNECTED')
  }
}
```

> 使用这些选项对象 [增强自定义元件厂](https://github.com/enhance-dev/enhance)

### 存储

供应初始状态加强,并将在 `store` 对象嵌入状态对象.

#### 节点

```javascript
import MyStoreData from './path/to/elements/my-store-data.mjs'
import enhance from '@enhance/ssr'
const html = enhance({
  elements: {
    'my-store-data': MyStoreData
  },
  initialState: { apps: [ { users: [ { name: 'tim', id: 001 }, { name: 'kim', id: 002 } ] } ] }
})
console.log(html`<my-store-data app-index="0" user-index="1"></my-store-data>`)
```

### 元素模板

```javascript
export default function MyStoreData({ html, state }) {
  const { attrs, store } = state
  const appIndex = attrs['app-index']
  const userIndex = attrs['user-index']
  const { id='', name='' } = store?.apps?.[appIndex]?.users?.[userIndex] || {}
  return `
<div>
  <h1>${name}</h1>
  <h1>${id}</h1>
</div>
  `
}
```

该商店用于将状态传递给树上的所有组件.

### 槽数

加强支持使用 [`slots` 在自定义元素模板中](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots)。 。 。 .

```javascript
export default function MyParagraph({ html }) {
  return html`
<p>
  <slot name="my-text">
    My default text
  </slot>
</p>
  `
}
```

您可以通过添加一个与要替换的槽名相匹配的槽属性来覆盖默认文本.

```html
<my-paragraph>
  <span slot="my-text">Let's have some different text!</span>
</my-paragraph>
```

#### 未命名槽

当您要为所有未分档的儿童节点创建容器元素时, 增强支持未命名的槽 .

```javascript
export default function MyButton({ html }) {
  return html`
<button>
  <slot>Submit</slot>
</button>
  `
}
```

```html
<my-button></my-button>

<my-button>Save</my-button>

```

### 变换

增强支持包含脚本和样式转换功能. 您将函数添加到 `scriptTransforms` 和(或) `styleTransforms` 并且可以随意改变内容, 只要返回你想要的输出.

```javaScript
import enhance from '@enhance/ssr'

const html = enhance({
  elements: {
    'my-transform-script': MyTransformScript
  },
  scriptTransforms: [
    function({ attrs, raw }) {
      // raw is the raw text from inside the script tag
      // attrs are the attributes from the script tag
      return raw + ' yolo'
    }
  ],
  styleTransforms: [
    function({ attrs, raw }) {
      // raw is the raw text from inside the style tag
      // attrs are the attributes from the style tag
      const { scope } = attrs
      return `
      /* Scope: ${ scope } */
      ${ raw }
      `
    }
  ]
})

function MyTransformScript({ html }) {
  return html`
<style scope="component">
  :host {
    display: block;
  }
</style>
<h1>My Transform Script</h1>
<script type=module>
  class MyTransformScript extends HTMLElement {
    constructor() {
      super()
    }
  }
  customElements.define('my-transform-script', MyTransformScript)
</script>
  `
}

console.log(html`<my-transform-script></my-transform-script>`)
```

### `context`

有时你需要通过状态 来决定巢中的孩子的定制元素。 避免通过多层次的嵌入元素传递属性的ium `context` 对象将状态添加到 .

父集上下文

```javaScript
export default function MyContextParent({ html, state }) {
  const { attrs, context } = state
  const { message } = attrs
  context.message = message

  return html`
    <slot></slot>
  `
}

```

儿童从提供上下文获取状态

```javaScript
export default function MyContextChild({ html, state }) {
  const { context } = state
  const { message } = context
  return html`
    <span>${ message }</span>
  `
}
```

撰写

```javaScript
<my-context-parent message="hmmm">
  <div>
    <span>
      <my-context-child></my-context-child>
    </span>
  </div>
</my-context-parent>
```

### `instanceID`

在从单一模板中渲染自定义元素时, 有时您可能需要瞄准特定实例 。 这个 `instanceID` 以 `state` 对象.

```javaScript
export default function MyInstanceID({ html, state }) {
  const { instanceID='' } = state

  return html`
<p>${instanceID}</p>
  `
}

```

### `bodyContent`

增强 SSR 输出整个有效的 HTML 页面,但您可以通过 `bodyContent: true` 以获取内容 `<body>` 键。 当您想要将 HTML 输出隔离到您正在撰写的自定义元素时, 这会有所帮助 .

```javaScript
const html = enhance({
  bodyContent: true,
  elements: {
    'my-paragraph': MyParagraph,
  }
})
const output = html`
<my-paragraph></my-paragraph>
  `
```

### 与 `<html>`, (中文(简体) ), `<head>`,以及 `<body>` 要素

加强安保部门改革将明智地合并其渲染 `<html>`, (中文(简体) ), `<head>`,以及 `<body>` 含有任何元素的元素(除非您选择使用) `bodyContent: true` 选项).

例如:

```js
const html = enhance({
  elements: {
    'my-content': MyContent,
  }
})

html`
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>My Website</title>
  </head>
  <body class="foo bar">
    <my-content></my-content>
  </body>
</html>
`
```

> P. S. 增强工作确实很好 [开始](https://begin.com/)。 。 。 .

## 常见问题

### @enhance/ssr 是什么？

对有模板和槽支持的自定义元素进行服务器侧渲染

### 如何安装 @enhance/ssr？

在项目目录运行 npm install @enhance/ssr，或使用 pnpm add / yarn add / bun add。

### @enhance/ssr 支持 TypeScript 吗？

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

### @enhance/ssr 支持 ESM 还是 CommonJS？

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

### @enhance/ssr 需要什么版本的 Node\.js？

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

### @enhance/ssr 可以商用吗？

@enhance/ssr 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @enhance/ssr 的下载量有多少？

根据 npm 官方下载统计，@enhance/ssr 在 2026/10/14 – 2026/11/12 这 30 天内被下载 3,135 次，日均约 105 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @enhance/ssr 还在维护吗？

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

