@saco/rem-plugin
v1.0.0
Published
Vite / Webpack rem adaptation plugin: postcss-pxtorem + root font-size injection
Maintainers
Readme
@saco/rem-plugin
Vite / Webpack 插件:px → rem(postcss-pxtorem)+ 启动时生成 runtime JS 并注入引用。
| 导出 | 用途 |
|------|------|
| vitePlugin | Vite |
| webpackPlugin | Webpack |
安装
Vite:
pnpm add -D @saco/rem-pluginWebpack(需额外安装 peer 依赖):
pnpm add -D @saco/rem-plugin postcss-loader html-webpack-pluginpostcss-loader:注入postcss-pxtorem(px → rem)html-webpack-plugin:向 HTML 注入 runtime<script src>
配置项
vitePlugin(options) / webpackPlugin(options) 共用:
| 字段 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| output | string | static/js | runtime 输出目录(须在 outDir 内,可写 dist/static/js) |
| designWidth | number | 1920 | 设计稿宽度 |
| rootValue | number | 16 | 设计稿下 1rem 对应的 px |
| minRoot | number | 12 | 根字号下限 |
| maxRoot | number | 16 | 根字号上限 |
| minPixelValue | number | 2 | 小于该值的 px 不转 rem |
| selectorBlackList | (string \| RegExp)[] | ['.norem'] | 不转换的选择器 |
开发时继续写 px。不想转换时可用 1Px / PX,或加类名 .norem。
Vite
import { defineConfig } from 'vite'
import { vitePlugin } from '@saco/rem-plugin'
export default defineConfig({
plugins: [
vitePlugin({
output: 'dist/static/js',
designWidth: 1920,
rootValue: 16,
minRoot: 12,
maxRoot: 16,
}),
],
})Webpack
确保工程已配置 postcss-loader,并使用 html-webpack-plugin 生成 HTML。
const { webpackPlugin } = require('@saco/rem-plugin')
module.exports = {
plugins: [
webpackPlugin({
output: 'dist/static/js',
designWidth: 1920,
rootValue: 16,
}),
],
}工作方式
- 业务配置:
vitePlugin({ output, designWidth, rootValue, ... }) - 启动 / 构建时:用包内已编译的 runtime 模块 + 配置,经 esbuild 生成业务侧 JS
- HTML 只注入:
<script src="..."></script>(无内联、无 data-*)
- 缓存:
node_modules/.cache/@saco/rem-plugin/saco-rem-runtime.js - 产物:由
output指定,默认static/js/saco-rem-runtime.js(相对 outDir)
