繁体   English   中英

尝试导入 tailwind 配置以访问颜色值作为 a.tsx 文件中的 js 变量会引发错误(使用带有 react-swc 插件的 vite 作为构建工具)

[英]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)

我在尝试将我定义的值从 tailwind.config.cjs 导入到 PageStats.tsx 时遇到问题。 有人可以为我做错什么提供明确的答案吗?

这是试图导入它的文件:

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;

这是我的 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: []
};

在我的 IDE (VSCode) 中没有错误,在我的浏览器中只有这些错误: 在此处输入图像描述

可能跟Vite有关系,不过我真的是一头雾水!

Vite 不支持开箱即用的 commonJS。 现在因为tailwind.config.cjs是 commonJS 你需要一些配置来让它工作:

import commonjs from 'vite-plugin-commonjs';

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

你需要vite-plugin-commonjs将 commonJS 转换成 JS 模块文件。

您还需要将'.cjs'添加到resolve.extensions列表中。 否则上面的插件也不会工作。 (这是因为 vite 默认的列表是['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'] source )。 我在这里停留了一段时间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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