[英]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.我在尝试将我定义的值从 tailwind.config.cjs 导入到 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:这是我的 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:在我的 IDE (VSCode) 中没有错误,在我的浏览器中只有这些错误:
Maybe it has something to do with Vite, however I am really clueless!可能跟Vite有关系,不过我真的是一头雾水!
Vite does not support commonJS out of box. Vite 不支持开箱即用的 commonJS。 Now since
tailwind.config.cjs
is commonJS you need some config to get it to work:现在因为
tailwind.config.cjs
是 commonJS 你需要一些配置来让它工作:
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.你需要
vite-plugin-commonjs
将 commonJS 转换成 JS 模块文件。
You also need to add '.cjs'
to resolve.extensions
list.您还需要将
'.cjs'
添加到resolve.extensions
列表中。 Otherwise above plugin won't work either.否则上面的插件也不会工作。 (This is because the default list of vite is
['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
source ). (这是因为 vite 默认的列表是
['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
source )。 I stuck here for a while.我在这里停留了一段时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.