使用mpx创建小程序并使用tailwind

发布时间 2023-07-20 10:13:11作者: deajax
# cli 创建项目
mpx create mpx
-project

# 切换到新的 mpx-project 中
cd mpx-project

把 @mpxjs/webpack-plugin 版本改为 2.8.32
# 安装包
yarn

执行:

yarn add -D tailwindcss weapp-tailwindcss-webpack-plugin postcss-rem-to-responsive-pixel

安装 weapp-tailwindcss

# npm / yarn /pnpm
yarn add -D weapp-tailwindcss
# 可以执行一下 patch 方法
npx weapp-tw patch

然后把下列脚本,添加进你的 package.json 的 scripts 字段里:

 "scripts": {
    "postinstall": "weapp-tw patch"
 }

在根目录下,创建一个 tailwind.config.js 文件,写入内容:

/** @type {import('tailwindcss').Config} */
module.exports = {
    // content 是用来指定让 tailwindcss 从哪些文件中提取字符串,来生成对应的工具类
    content: ['./src/**/*.{html,js,ts,mpx}'],
    theme: {
        extend: {}
    },
    plugins: [],
    // 去除 preflight ,因为 preflight.css 主要用来 reset h5 的样式的
    // 如果你有多端需求,可以通过环境变量来控制这个值
    corePlugins: {
        preflight: false
    }
}

接着在原先的 postcss.config.js 基础上,加上 tailwindcss 和 postcss-rem-to-responsive-pixel

module.exports = {
  plugins: [
    require('tailwindcss')(),
    require('autoprefixer')({ remove: false }),
    require('postcss-rem-to-responsive-pixel')({
      // 下面这段配置项的意思是,1rem转化为32rpx,* 的意思是所有的 rem 会被转化
      rootValue: 32,
      propList: ['*'],
      transformUnit: 'rpx'
    })
  ]
}

在 vue.config.js 注册插件:

// vue.config.js
const { defineConfig } = require('@vue/cli-service')
const { UnifiedWebpackPluginV5 } = require('weapp-tailwindcss/webpack')

module.exports = defineConfig({
  pluginOptions: {
    mpx: {
      srcMode: 'wx',
      plugin: {
        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: {}
    }
  },
  /**
   * 如果希望node_modules下的文件时对应的缓存可以失效,
   * 可以将configureWebpack.snap.managedPaths修改为 []
   */
  configureWebpack(config) {
    config.plugins.push(new UnifiedWebpackPluginV5({
      appType: 'mpx'
    }))
  }
})

在 app.mpx 中引入 tailwindcss

<style>
@tailwind base;
@tailwind utilities;
@tailwind components;
    /* 如果你使用 scss,你可以在 style标签上加上 lang="scss" 然后使用@import */
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
</style>

删除 package.json 里的 eslint

"devDependencies": {
-    "@mpxjs/eslint-config": "^1.0.5",
-    "@mpxjs/vue-cli-plugin-mpx-eslint": "^2.0.0",
-    "eslint": "^7.0.0",
},

启动项目

npm run serve 

#或者
yarn serve

打开微信小程序开发者工具,选择导入,找到项目下的dist文件夹导入。