问题描述
我正在尝试在我的 scss 文件中使用这些变量,以便将来可以直接从这里更改我的主题。但它显示我解析错误,这在以前的项目中没有。
这是一个带有打字稿的 React CRA 项目。
//App.tsx
import React from "react";
import "./App.scss";
const lightTheme = {
"--primary": "#27AE60","--text-primary": "#000000","--background-primary": "#ffffff","--background-secindary": "#fafafa",} as React.Cssproperties;
const App = () => {
return <div className="App" style={lightTheme}></div>;
};
export default App;
我现在可以将它们用作 -
//App.scss
body {
color: var(--primary);
}
我的 package.json 文件 -
{
"name": "management-portal","version": "0.1.0","private": true,"dependencies": {
"@testing-library/jest-dom": "^5.11.4","@testing-library/react": "^11.1.0","@testing-library/user-event": "^12.1.10","@types/jest": "^26.0.15","@types/node": "^12.0.0","@types/react": "^16.9.53","@types/react-dom": "^16.9.8","react": "^17.0.1","react-dom": "^17.0.1","react-router-dom": "^5.2.0","react-scripts": "4.0.1","sass": "^1.32.5","typescript": "^4.0.3","web-vitals": "^0.2.4"
},"scripts": {
"start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject"
},"browserslist": {
"production": [
">0.2%","not dead","not op_mini all"
],"development": [
"last 1 chrome version","last 1 firefox version","last 1 safari version"
]
}
}
但它给我带来了这个错误......
Line 9:3: Parsing error: Unexpected token,expected ";"
7 | "--background-primary": "#ffffff",8 | "--background-secindary": "#fafafa",> 9 | } as React.Cssproperties;
| ^
10 |
11 | const App = () => {
12 | return <div className="App" style={lightTheme}></div>;
虽然我期待以下结果 - Expected result in browser
我有解决该错误的方法,效果很好。但是我无法在之前的代码中找到我的错误。在这里——
import React from "react";
import "./App.scss";
const lightTheme: any = {
"--primary": "#27AE60",};
const App = () => {
return <div className="App" style={lightTheme}></div>;
};
export default App;
解决方法
我成功克隆了您的存储库并找出了上述错误的原因。
您在 eslintConfig
中缺少 package.json
属性:
{
"name": "management-portal","version": "0.1.0","private": true,"dependencies": {
"@testing-library/jest-dom": "^5.11.4","@testing-library/react": "^11.1.0","@testing-library/user-event": "^12.1.10","@types/jest": "^26.0.15","@types/node": "^12.0.0","@types/react": "^16.9.53","@types/react-dom": "^16.9.8","react": "^17.0.1","react-dom": "^17.0.1","react-router-dom": "^5.2.0","react-scripts": "4.0.1","sass": "^1.32.5","typescript": "^4.0.3","web-vitals": "^0.2.4"
},"scripts": {
"start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject"
},"eslintConfig": { <----- This one
"extends": "react-app"
},"browserslist": {
"production": [
">0.2%","not dead","not op_mini all"
],"development": [
"last 1 chrome version","last 1 firefox version","last 1 safari version"
]
}
}
您可能需要添加此 yarn add -D eslint-config-react-app
这是一个小的修复,但此属性是由 CRA cli 生成的。不知道为什么您在使用该命令后会遗漏它(也许您的应用已被弹出,或者您正在临时将 Typescript 添加到您的应用中)。