简体   繁体   中英

Trying to import the tailwind config to access color values as js vars in a .tsx file throws an error (using vite with react-swc plugin as build tool)

I have a problem trying to import my defined values from tailwind.config.cjs into PageStats.tsx. Could someone provide me with a clear answer to what I am doing wrong?

This is the file trying to import it:

import React from "react";
import Card from "../components/Card";
import resolveConfig from "tailwindcss/resolveConfig";
import tailwindConfig from "../../tailwind.config.cjs";

type Props = {};
const mockData = [
...
];

const cssConfig = resolveConfig(tailwindConfig);
let accent = "#8884d8";
if (cssConfig && cssConfig.theme && cssConfig.theme.colors) {
accent = cssConfig?.theme?.color['accent'];
};

function PageStats({}: Props) {
  return (
  [...]
  );
}

export default PageStats;

This is my tailwind.config.cjs:

/** @type {import('tailwindcss').Config} */

module.exports = {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}", "./public/*.svg"],
  theme: {
    extend: {
      keyframes: {
        gradient: {
          '0%, 100%': { 'background-size': '400% 400%', 'background-position': '0% 50%' },
          '50%': { 'background-size': '200% 200%', 'background-position': '100% 50%' },
        },
      },
      animation: {
        gradient: 'gradient 7s ease infinite',
      },
      boxShadow: {
        'outline': '0 0 8px 2px rgba(0, 0, 0, 0.5)',
      },
      colors: {
        'primary': '#0F172A',
        'secondary': '#181E41',
        'tertiary': '#2C2F54',
        'pop': '#FFCDB2',
        'pop-2': '#ff9090',
        'accent': '#574AE2',
        'success': '#2F9C95',
        'warning': '#F2CD5D',
        'danger': '#FF1053',
        'info': '#4465FF', 
      },
      borderRadius: {
        'ce': '12px'
      }
    }
  },
  plugins: []
};

There is no error in my IDE (VSCode), only these errors in my browser: 在此处输入图像描述

Maybe it has something to do with Vite, however I am really clueless!

Vite does not support commonJS out of box. Now since tailwind.config.cjs is commonJS you need some config to get it to work:

import commonjs from 'vite-plugin-commonjs';

export default {
  plugins: [commonjs()],
  resolve: {
    extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json', '.cjs']
  }
}

You need vite-plugin-commonjs which transpile commonJS into JS module file.

You also need to add '.cjs' to resolve.extensions list. Otherwise above plugin won't work either. (This is because the default list of vite is ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'] source ). I stuck here for a while.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM