tailwindcss2: 项目中集成/cra/postcss7

在比较老的项目中集成 tailwindcss2

01 安装基本依赖

主要是 postcss7

# 一般项目已经有 postcss7了
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
# 已经有了,就不用安装
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat autoprefixer@^9

02 添加 tailwind 配置文件

这里使用 npx

npx tailwindcss-cli@latest init

配置如下

module.exports = {
  purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

03 添加 postcss 配置

如果是 craco

// craco.config.js
module.exports = {
  style: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
}

我的实际项目

{
  // Options for PostCSS as we reference these options twice
  // Adds vendor prefixing based on your specified browser support in
  // package.json
  loader: require.resolve('postcss-loader'),
  options: {
    // Necessary for external CSS imports to work
    // https://github.com/facebook/create-react-app/issues/2677
    ident: 'postcss',
    plugins: () => [
      require('postcss-flexbugs-fixes'),
      require('postcss-preset-env')({
        autoprefixer: {
          flexbox: 'no-2009',
        },
        stage: 3,
      }),
      // add tailwindcss plugin
      require('tailwindcss')(path.resolve(paths.appSrc, '../tailwind.config.js')),
      require('autoprefixer')({
        overrideBrowserslist: ['>0.5%', 'not ie < 11', 'not op_mini all'],
      }),
    ],
    sourceMap: isEnvProduction && shouldUseSourceMap,
  },
},

04 在项目中的 index.css 添加 tailwind

基本配置

@tailwind base;
@tailwind components;
@tailwind utilities;
cra react tailwindcss craco