rem-adjuster
v1.0.0
Published
A utility for rem-based responsive design
Maintainers
Readme
rem-adjuster
一个小巧的 rem 自适应工具与 Vue 插件,提供:
- 动态设置 HTML 根字体(基于设计稿宽度)
- 将 px/数字 转换为 rem 的工具方法
- 支持 Vue2 / Vue3 的插件安装方式
安装 使用 npm:
npm install rem-adjuster --save或使用 yarn:
yarn add rem-adjuster开发时请运行:
npm install
npm test快速开始 浏览器或模块化环境:
import ResponsiveRem, { setRem, ResponsiveRem as RR } from 'rem-adjuster';
// 直接在页面中启动(会添加 resize 监听)
const stop = setRem({ baseWidth: 1440, baseFontSize: 16 });
// 创建实例并使用转换方法
const rem = new RR({ baseFontSize: 16 });
rem.convert(16); // '1rem'
rem.convert('16px'); // '1rem'
rem.convertStyles({ width: 16, zIndex: 10 });
Vue 插件
import { default as RemPlugin } from 'rem-adjuster';
// 或 import RemPlugin from 'rem-adjuster/dist/index.js'
// Vue 3
const app = createApp(App);
app.use(RemPlugin, { baseFontSize: 16 });
// 在组件中通过 this.$rem(...) 或 this.$remStyles(...) 使用
// Vue 2
Vue.use(RemPlugin, { baseFontSize: 16 });
// 在组件中通过 this.$rem(...) 或 this.$remStyles(...) 使用
插件支持传入已创建的实例:
const remInstance = new ResponsiveRem({ baseFontSize: 16 });
app.use(RemPlugin, { remInstance });API 类型定义(主要选项):
RemOptions = {
baseWidth?: number = 1440, // 设计稿宽度(px)
baseFontSize?: number = 16, // 根字体基准(px)
minScale?: number = 0.8,
maxScale?: number = 1.2,
convertNumericString?: boolean = true, // 是否把纯数字字符串("16")视为 px
unitlessProps?: Array<string> | Set<string> // 自定义无单位属性
}主要导出:
- setRem(options?: RemOptions): () => void
启动全局根字体自适应,返回 stop() 函数用于移除监听。
- ResponsiveRem
- constructor(options?: RemOptions)
- convert(px: number | string): string | number
- convertStyles(styles: Object): Object
- stop(): void
注意事项:
默认内置了一个较全的“无单位属性”列表(借鉴 React 的 unitlessNumbers),这些属性的数字值不会被转换为 rem(例如 zIndex、opacity、fontWeight、lineHeight 等)。如果需要,可通过 options.unitlessProps 扩展或覆盖。
默认将 '16'(纯数字字符串)视为像素并转换为 rem;如果不需要此行为,可设置 convertNumericString: false。
测试与开发 仓库内已包含 Jest 测试:
npm install
npm test测试覆盖主要场景:基本转换、无单位属性行为、kebab-case 属性支持、stop() 清理、SSR 构造行为、以及插件在 Vue2/Vue3 下的挂载
构建与发布
- 源码位于 src,发布前通过 Babel 构建到 dist:
npm run build- package.json 中 prepare 脚本会在 npm publish 时自动构建。
