Skip to content

内置插件

Oxc transformer 内置支持流行的转换插件,以改善开发体验和构建性能。

标签模板转义

启用时,标签模板字面量内的 </script> 序列会被转义,以防止浏览器过早关闭周围的 <script> 标签。这可以避免当 JavaScript 直接嵌入 HTML 时的解析错误和潜在的 XSS 漏洞。

建议

当转换后的输出可能直接嵌入 HTML <script> 标签时,启用此选项。如果不启用,包含 </script> 的标签模板字面量在嵌入 HTML <script> 标签时可能会出错。详见 oxc-project/oxc#15306

javascript
import { transform } from "oxc-transform";

const result = await transform("lib.js", sourceCode, {
  plugins: {
    taggedTemplateEscape: true,
  },
});

例如,foo`</script>` 会被转换为一个辅助函数调用,其中 </script> 序列被转义为 <\/script>

Styled Components

styled-components 插件添加了对 styled-components 的全面支持,包括服务器端渲染、样式压缩和增强的调试能力。

基本用法

javascript
import { transform } from "oxc-transform";

const result = await transform("Component.jsx", sourceCode, {
  plugins: {
    styledComponents: {
      displayName: true,
      ssr: true,
      fileName: true,
      minify: true,
    },
  },
});

示例

输入:

jsx
import styled from "styled-components";

const Button = styled.div`
  color: blue;
  padding: 10px;
`;

输出(使用默认选项):

jsx
import styled from "styled-components";

const Button = styled.div.withConfig({
  displayName: "Button",
  componentId: "sc-1234567-0",
})(["color:blue;padding:10px;"]);

配置选项

核心选项

选项类型默认值描述
displayNamebooleantrue在附加的 CSS 类名中添加组件名,便于调试
ssrbooleantrue添加唯一组件 ID 以避免服务器端渲染时的校验和不匹配
fileNamebooleantrue控制是否在 displayName 前添加文件名前缀

模板字面量选项

选项类型默认值描述
transpileTemplateLiteralsbooleantrue将模板字面量转换为更小的表示以减小包大小
minifybooleantrue通过移除空白和注释来压缩 CSS 内容

高级选项

选项类型默认值描述
purebooleanfalse添加 /*#__PURE__*/ 注释以更好地进行 tree-shaking
namespacestringundefined为组件 ID 添加命名空间前缀
meaninglessFileNamesstring[]["index"]被认为对组件命名无意义的文件名列表

尚未实现

选项类型默认值描述
cssPropbooleantrueJSX css prop 转换(计划中)
topLevelImportPathsstring[][]自定义导入路径处理(计划中)

支持的导入模式

该插件支持多种 styled-components 导入模式:

javascript
// 默认导入
import styled from "styled-components";

// 命名空间导入
import * as styled from "styled-components";

// 命名导入
import { createGlobalStyle, css, keyframes } from "styled-components";

// Native 和 primitives
import styled from "styled-components/native";
import styled from "styled-components/primitives";

功能支持

✅ 完全支持:

  • 用于调试的显示名称
  • 在显示名称中添加文件名前缀
  • 服务器端渲染支持
  • 模板字面量转译
  • CSS 压缩
  • 命名空间前缀
  • 调用表达式的纯注解

⚠️ 部分支持:

  • 纯注解(仅支持调用表达式,由于打包工具限制不支持标签模板)

❌ 尚未实现:

  • JSX css prop 转换
  • 自定义导入路径处理