banner
banner
banner
NEWS LETTER

Taro 工程化:分包、Tailwind 设计系统与别名

Scroll down

项目的效率上限在这一层就定死了:能不能直接写 w-300、text-28、bg-tag3,取决于配置里有没有把这些刻度注册进去。
这篇把地基拆成五块——编译配置与别名、分包策略、Tailwind 设计系统、weapp-tailwindcss 转译、以及 utils / enums / 全局类型这一小层工具约定,最后补上构建期最容易踩的几个点。
顺序仍然是「先写配置,再写页面」。

背景

所有页面都在用同一套尺寸语言:设计师说「这里 28 号字、间距 32」,代码里就写 text-28 mt-32。这套语言要成立,必须先把 750 设计稿的刻度批量注册进 Tailwind,而不是每个页面各自 style={{ fontSize: 28 }}。

同理,小程序有主包 2MB 的硬限制,练习页越堆越多时必须分包;import 路径越长越难维护,必须配别名。这些都发生在写第一个页面之前。

实现

1. 编译配置与别名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// config/index.ts
export default defineConfig(async (merge) => {
const baseConfig: UserConfigExport = {
projectName: 'taro-weapp',
designWidth: 750, // 设计稿宽度,决定 px → rpx 的换算基准
deviceRatio: { 640: 2.34 / 2, 750: 1, 375: 2, 828: 1.81 / 2 },
sourceRoot: 'src',
outputRoot: 'dist', // 小程序产物目录,project.config.json 指向它
framework: 'react',
compiler: {
type: 'webpack5',
prebundle: { enable: false, force: true },
},
cache: { enable: false },
mini: {
postcss: {
pxtransform: { enable: true, config: {} }, // 750 基准的 px → rpx
url: { enable: true, config: { limit: 1024 } }, // 小于 1024 的图片转 base64
cssModules: { enable: false },
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
chain.merge({
plugin: {
install: {
plugin: UnifiedWebpackPluginV5, // weapp-tailwindcss
args: [{ appType: 'taro' }],
},
},
})
},
},
alias: {
'@/*': path.resolve(__dirname, 'src/*'),
'@utils/*': path.resolve(__dirname, 'src/utils/*'),
'@enums/*': path.resolve(__dirname, 'src/enums/*'),
'@api/*': path.resolve(__dirname, 'src/api/*'),
},
}

return merge({}, baseConfig, process.env.NODE_ENV === 'development' ? devConfig : prodConfig)
})
配置 作用 踩坑点
designWidth: 750 px → rpx 的换算基准 设计稿不是 750 时必须改,否则整站尺寸按比例全错
pxtransform.enable 自动把 px 转 rpx 想写「真 px」要用大写 PX 或加白名单
url.limit: 1024 小图转 base64 调大能减少请求,但会撑大包体
prebundle.enable: false 关掉依赖预打包 首次构建慢,但能避开大量「改了代码没生效」的问题
cache.enable: false 关掉 Webpack 持久缓存 同上,开发期换确定性
alias + TsconfigPathsPlugin 两处都要配 只配一处会出现「TS 能过、构建报错」或反过来

别名这条值得单独记住:alias 是给编译器的,TsconfigPathsPlugin 是给 webpack 解析的。两处各写一遍很烦,但少写一处就会得到「IDE 一片红但能跑」或者「IDE 不报错但构建失败」二选一。

多端构建脚本直接铺开九个平台:

1
2
3
4
5
6
7
8
9
10
11
{
"build:weapp": "taro build --type weapp",
"build:swan": "taro build --type swan",
"build:alipay": "taro build --type alipay",
"build:tt": "taro build --type tt",
"build:h5": "taro build --type h5",
"build:rn": "taro build --type rn",
"dev:weapp": "npm run build:weapp -- --watch",
"dev:h5": "npm run build:h5 -- --watch",
"test": "jest"
}

实际只会用到 1~2 个,其余保留是为了「以后想扩端不用回头改配置」。

2. 分包与页面跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/app.config.ts
export default defineAppConfig({
entryPagePath: 'pages/entry', // 启动页不是 index
pages: ['pages/index', 'pages/entry'], // 主包只留 2 页
subPackages: [
{ root: 'sub', pages: ['pages/todo/index', 'pages/turntable/index' /* 其余练习页 */] },
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'Taro 练习',
navigationBarTextStyle: 'black',
},
})

分包的原则是按「首次进入用不到」切:启动页只需要自己和主菜单,其余十几个练习页都是用户点击后才需要,一次切干净。主包因此一直保持在 2MB 限制以内,冷启动加载的代码量也小得多。

从启动页进主菜单的跳转要用对 API:

1
2
3
4
5
// 启动页 → 主菜单(主菜单是普通页面,不是 tabBar 页)
Taro.navigateTo({ url: '/pages/index' })

// 如果希望启动页不再留在栈里,用 reLaunch
Taro.reLaunch({ url: '/pages/index' })

3. Tailwind 设计系统

① 批量生成像素刻度

1
2
3
4
5
6
7
8
9
10
11
const pxs = [
1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 70, 72, 76, 80, 84, 88, 90,
96, 100, 112, 120, 160, 180, 230, 280, 300, 400,
]

const extendsPxs = () => {
const extended = {}
pxs.forEach((px) => { extended[px] = `${px}px` })
return extended
}

挂到多个维度上,注意统一放在 extend 里,只写一处:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module.exports = {
content: ['./public/index.html', './src/**/*.{html,js,ts,jsx,tsx,vue}'],
corePlugins: {
preflight: false, // ★ 小程序端要关掉,否则和基础样式打架
},
theme: {
fontSize: {
24: ['24px', '40px'], // [字号, 行高],数字即类名:text-24
28: ['28px', '44px'],
32: ['32px', '48px'],
36: ['36px', '52px'],
},
textColor: {
secondary: 'rgba(0, 0, 0, 0.65)',
placeholder: 'rgba(0, 0, 0, 0.45)',
other: 'rgba(0, 0, 0, 0.25)',
white: '#FFF',
black: '#000',
primary: 'rgba(0, 0, 0, 0.85)',
whiteOpacity: 'rgba(255, 255, 255, 0.5)',
grayOpacity: 'rgba(0, 0, 0, 0.5)',
},
backgroundColor: {
white: '#FFF',
black: '#000',
primary: 'rgba(0, 0, 0, 0.85)',
glassOpacity: 'rgba(133, 204, 0, 0.25)',
whiteOpacity: 'rgba(255, 255, 255, 0.5)',
grayOpacity: 'rgba(0, 0, 0, 0.5)',
gray: '#F5F5F5',
mask: 'rgba(0, 0, 0, 0.75)',
tag1: '#5994F4', // 10 色标签板
tag2: '#69DBAD',
tag3: '#657A99',
tag4: '#F6BB3D',
tag5: '#6D6DF7',
tag6: '#7BD4F5',
tag7: '#9467B8',
tag8: '#F58F4C',
tag9: '#138684',
tag10: '#EE8EB3',
},
divideColor: { base: 'rgba(0, 0, 0, .1)' },
borderColor: { base: 'rgba(0, 0, 0, 0.25)' },
boxShadow: { base: '0px 0px 32px 0px rgba(0, 0, 0, 0.1)' },
},
extend: {
width: { auto: 'auto', full: '100%', screen: '100vw', fit: 'fit-content', ...extendsPxs() },
height: { auto: 'auto', full: '100%', screen: '100vh', fit: 'fit-content', ...extendsPxs() },
spacing: { ...extendsPxs() }, // 同时覆盖 p-* / m-* / gap-*
minWidth: { ...extendsPxs() },
maxWidth: { ...extendsPxs() },
maxHeight: { ...extendsPxs() },
borderRadius: { circle: '50%', ...extendsPxs() },
},
}

于是全站可以直接写 w-300、h-230、p-30、m-10、rounded-8、rounded-circle——这套刻度是项目里出现频率最高的 className 来源。

『fontSize 用数字当 key』:fontSize: { 24: ['24px', '40px'] } 生成的就是 text-24 / text-28 / text-32 / text-36,比 text-sm / text-base 这种语义化命名更贴合中文设计稿的沟通方式——设计师说「这里 28 号字」,直接写 text-28,不用在脑子里做一次映射。

『tag1~tag10 是整个项目的视觉底座』:所有手写页面都用 bg-tag1~bg-tag10 上色,好处是不用记十六进制,也不会出现「同一个蓝用了五个近似值」。

② preflight: false 为什么必须关

1
2
3
4
corePlugins: {
// preflight 主要是给 h5 的;如果需要同时开发小程序和 h5,应该用环境变量分别控制
preflight: false,
}

preflight 会重置所有元素的默认样式(h1 字号、ul 缩进等)。在小程序端它会和基础组件打架——button、input 的原生外观被一并抹掉,反而要花更多样式补回来。真要 h5 和小程序都做,按 process.env.TARO_ENV 分支开合更严谨。

4. weapp-tailwindcss 的接入

小程序的 WXSS 对类名有额外限制:含 [ ] . / % # 这类特殊字符的类名必须转义才能被正确匹配。Tailwind 的任意值类名(w-[270px]、text-[40px])恰好全是这类字符,所以不转译时它们不是「不支持」,而是选择器写出来匹配不上。

weapp-tailwindcss 做的就是把这批类名转成小程序能识别的转义形式。接入只需在 config/index.ts 的 mini.webpackChain 里挂插件:

1
2
3
4
5
6
7
8
chain.merge({
plugin: {
install: {
plugin: UnifiedWebpackPluginV5,
args: [{ appType: 'taro' }],
},
},
})

5. 全局样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/app.scss
@import "tailwindcss/base";
@import "tailwindcss/utilities";
@import "tailwindcss/components";

/* 重置小程序原生 radio:只留语义,不留视觉 */
radio .wx-radio-input { border: none; border-radius: 50%; width: 0px; height: 0px; }
radio .wx-radio-input.wx-radio-input-checked {
border-color: transparent !important;
background: transparent !important;
}
radio .wx-radio-input.wx-radio-input-checked::before {
width: 0px; height: 0px; line-height: 0px;
color: transparent; background: transparent;
transform: translate(-50%, -50%) scale(1);
}

层层叠叠的 !important 是在小程序里覆盖原生组件样式的标准手段——原生组件的内部结构拿不到更细的选择器层级,只能靠优先级硬顶。

src/style/tailwind.css 则是 Tailwind 的 base 重置(box-sizing、img { max-width: 100%; height: auto; }、表单元素 font-family: inherit),由 src/index.html 引入,只在 h5 端生效。

6. 工具函数与枚举

配置层搭好之后,剩下的是「每个页面都会用到、但又不能塞进组件里」的东西:日期处理、Canvas 上下文、业务枚举、全局类型声明。它们收在 src/utils、src/enums、types/global.d.ts 三处,代码都很短,价值在约定而不是实现。

① utils/date.ts:dayjs 插件集中 extend

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import dayjs from 'dayjs'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
import isBetween from 'dayjs/plugin/isBetween'
import isToday from 'dayjs/plugin/isToday'
import isYesterday from 'dayjs/plugin/isYesterday'

// 统一在这里 extend,业务侧直接用 dayjs 即可
dayjs.extend(isSameOrBefore)
dayjs.extend(isSameOrAfter)
dayjs.extend(isBetween)
dayjs.extend(isToday)
dayjs.extend(isYesterday)

export default dayjs

dayjs 的插件是全局副作用,分散 extend 容易漏,一漏就是「在我机器上能用」。集中到一个文件再 export default dayjs,业务里 import dayjs from '@utils/date' 就自带全部能力。

周几转换和补零这类小函数也放这里:

1
2
3
4
const WEEK = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
export const getWeek = (date: Date) => WEEK[date.getDay()]

export const handTimeDiff = (val: number) => (val < 10 ? `0${val}` : `${val}`)

② utils/canvas.tsx:Canvas 上下文封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { createSelectorQuery, getWindowInfo } from '@tarojs/taro'

export const getCanvasCtx = async (selectorID = '', width: number, height: number) => {
return new Promise<{ ctx: CanvasRenderingContext2D; canvas: any }>((resolve, reject) => {
const query = createSelectorQuery()
query.select(`#${selectorID}`).fields({ node: true, size: true }).exec((res) => {
if (!res[0]) {
reject({ msg: '获取canvas失败' })
return
}

const canvas = res[0].node
const ctx = canvas.getContext('2d')

// 安卓兼容:pixelRatio >= 3 时压成 1,否则 canvasToTempFilePath 会 native buffer 超限
const { pixelRatio } = getWindowInfo()
const dpr = pixelRatio >= 3 ? 1 : pixelRatio

canvas.width = width * dpr
canvas.height = height * dpr
ctx.scale(dpr, dpr)

// ✗ 错误写法:工具函数里不应有任何绘制副作用
// drawCanvas(ctx, canvas)

resolve({ ctx, canvas })
})
})
}

三个正确的地方:

  1. fields({ node: true, size: true }) —— canvas 2d 必须靠 node: true 才能拿到节点。
  2. canvas.width / height 必须显式赋值,否则默认 300×150。
  3. ctx.scale(dpr, dpr) 让后续绘制按逻辑像素算。

顺带一提,drawCanvas 里的 ctx.fontSize = 20 不是标准 2D API,正确写法是 ctx.font = '20px sans-serif'。这一行之所以没出问题,是因为签名文字本来就会被后续 drawImage 覆盖,属于可以顺手删掉的瑕疵。

③ enums/itinerary.ts:const enum 与 enum 怎么选

1
2
3
4
5
6
7
8
9
10
11
12
// 字段类型:只用来做 switch 分支
export const enum KeyCodeType {
TEXT = 1, DATE = 2, MULTI = 3, LABEL = 4,
MODIFY_BY = 5, MODIFY_TIME = 6, CREATE_BY = 7, CREATE_TIME = 8,
}

// 通知类型:需要渲染成选项列表
export enum NoticeType {
NO_NOTICATION = 0, // 无通知
SAMEDAY_NOTICE = 1, // 当天通知
ONEDAY_NOTICE = 2, // 1 天前通知
}
  • const enum 编译期完全内联,产物里不生成对象,体积更小;代价是不能在运行时遍历。
  • enum 保留运行时对象,可以 Object.keys() 遍历,适合做下拉 / 筛选。

判断依据就是要不要在运行时遍历。字段类型只用于 switch 分支,选 const enum;通知类型要渲染成选项列表,选 enum。

④ types/global.d.ts:全局类型声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <reference types="@tarojs/taro" />

declare module '*.png'
declare module '*.gif'
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.svg'
declare module '*.css'
declare module '*.less'
declare module '*.scss'
declare module '*.sass'
declare module '*.styl'

declare namespace NodeJS {
interface ProcessEnv {
NODE_ENV: 'development' | 'production'
TARO_ENV: 'weapp' | 'swan' | 'alipay' | 'h5' | 'rn' | 'tt' | 'quickapp' | 'qq' | 'jd'
TARO_APP_ID: string
}
}

两个作用:让静态资源可以 import(否则 import entryBg from '../style/images/entryBg.png' 直接报错),以及让 process.env.TARO_ENV 在多端条件编译时有类型提示。TARO_APP_ID 的存在意义是按环境注入不同 appid,避免手动去改 dist/project.config.json——那个文件是构建产物,改了下次构建就被覆盖。

7. 测试

1
2
3
4
5
6
// jest.config.ts
const defineJestConfig = require('@tarojs/test-utils-react/dist/jest.js').default
module.exports = defineJestConfig({
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/__tests__/?(*.)+(spec|test).[jt]s?(x)'],
})
1
2
3
4
5
6
7
8
9
10
11
// __tests__/index.test.js
import TestUtils from '@tarojs/test-utils-react'

describe('Testing', () => {
test('Test', async () => {
const testUtils = new TestUtils()
await testUtils.createApp()
await testUtils.PageLifecycle.onShow('pages/index')
expect(testUtils.html()).toMatchSnapshot()
})
})

踩坑

  • 别名必须两处配:config/index.ts 的 alias 给编译器,TsconfigPathsPlugin 给 webpack。少一处就是「IDE 与构建二选一报错」。
  • preflight: false 是必须的:小程序端开着它会把 button / input 的原生样式冲掉。
  • 宽度 / 高度刻度只在 extend 写一次:theme.width 是整体替换、extend.width 是合并追加,两处都写会让默认比例类名(w-1/2 等)静默失效。
  • 任意值类名的坑在转义不在语法:w-[270px] 需要转译成转义形式才能匹配,weapp-tailwindcss 负责这层;别把它理解成「WXSS 不支持」。
  • switchTab 只认 tabBar 页:没配 tabBar 的项目里调它必然 fail,普通页面跳转用 navigateTo / reLaunch。
  • designWidth 与设计稿强绑定:换 375 设计稿时必须同步改这里,否则全站尺寸按比例错。
  • **cache.enable: false + prebundle.enable: false**:牺牲构建速度换「所见即所得」,开发期推荐;上线前可以打开。
  • **不要手改 dist**:project.config.json 里 miniprogramRoot 指向 dist/,改 config/*.ts 再构建才对。
  • 工具函数不要有副作用:getCanvasCtx 里那次绘制是最典型的反面例子,纯函数一旦掺入业务绘制,复用一次就出问题。
  • **新代码统一用 getWindowInfo**:getSystemInfoSync 已标记废弃,utils/canvas.tsx 用的是新 API,旧页面还留着老的,迁移时一起换掉。
其他文章
目录导航 置顶
  1. 1. 背景
  2. 2. 实现
    1. 2.1. 1. 编译配置与别名
    2. 2.2. 2. 分包与页面跳转
    3. 2.3. 3. Tailwind 设计系统
    4. 2.4. 4. weapp-tailwindcss 的接入
    5. 2.5. 5. 全局样式
    6. 2.6. 6. 工具函数与枚举
    7. 2.7. 7. 测试
  3. 3. 踩坑
请输入关键词进行搜索