Mpx
安装
- npm
- Yarn
- pnpm
- Bun
npm install -D tailwindcss @tailwindcss/postcss postcss weapp-tailwindcss
yarn add --dev tailwindcss @tailwindcss/postcss postcss weapp-tailwindcss
pnpm add -D tailwindcss @tailwindcss/postcss postcss weapp-tailwindcss
bun add --dev tailwindcss @tailwindcss/postcss postcss weapp-tailwindcss
然后把下列脚本,添加进你的 package.json 的 scripts 字段里:
package.json
"scripts": {
"postinstall": "weapp-tw patch"
}
这是为了给 tailwindcss@4 打上支持 rpx 单位的补丁,否则它会把 rpx 认为是一种颜色
配置
更改 mpx.config.js 注册 weapp-tailwindcss
mpx.config.js
const { defineConfig } = require('@vue/cli-service')
const { UnifiedWebpackPluginV5 } = require('weapp-tailwindcss/webpack')
const path = require('node:path')
module.exports = defineConfig({
outputDir: `dist/${process.env.MPX_CURRENT_TARGET_MODE}`,
pluginOptions: {
mpx: {
plugin: {
srcMode: 'wx',
hackResolveBuildDependencies: ({ files, resolveDependencies }) => {
const path = require('path')
const packageJSONPath = path.resolve('package.json')
if (files.has(packageJSONPath)) files.delete(packageJSONPath)
if (resolveDependencies.files.has(packageJSONPath)) {
resolveDependencies.files.delete(packageJSONPath)
}
}
},
loader: {}
}
},
configureWebpack(config) {
// 添加的代码在这里
config.plugins.push(
new UnifiedWebpackPluginV5({
rem2rpx: true,
cssEntries: [
// 你 @import "weapp-tailwindcss"; 那个文件绝对路径
path.resolve(__dirname, './src/app.css'),
],
})
)
}
})
tailwindcss@4 必须配置
cssEntries并且使用绝对路径,否则tailwindcss生成的类名不会参与转译。
添加 postcss.config.js 注册 @tailwindcss/postcss
postcss.config.js
module.exports = {
plugins: [
require('@tailwindcss/postcss')()
]
}
添加样式
在 src/app.css 中引入 weapp-tailwindcss:
src/app.css
@import "weapp-tailwindcss";
然后在项目目录下,小程序全局的 app.mpx 中,通过 @import 引入该文件:
app.mpx
<style lang="css">
@import "./app.css";
</style>
更改好配置之后,直接启动即可
