我正在尝试使用 webpack 创建一个带有typescript的 React 项目。但我无法让 CSS module正常工作。尝试在typescript中导入 CSS 文件时,我不断收到此错误:
ERROR in src/components/Button.module.css:1:0
[unknown]: Parsing error: Declaration or statement expected.
> 1 | .myButton {
2 | box-shadow: 0px 0px 0px -1px #1c1b18;
3 | background:linear-gradient(to bottom, #eae0c2 5%, #ccc2a6 100%);
4 | background-color:#eae0c2;
ℹ 「wdm」: Failed to compile.
对我来说,这看起来像 webpack 期望 css 文件包含有效的typescript,但我不确定。我试着环顾四周,虽然很多人似乎都在努力将 typescript 和 CSS module一起使用,但我找不到任何有类似问题的人。
我像这样导入了 CSS 文件:Button.tsx
import React from "react";
import "./Button.module.css";
export class Button extends React.Component{
...
}
这是我要导入的 CSS 文件。按钮.module.css:
.myButton {
box-shadow: 0px 0px 0px -1px #1c1b18;
background:linear-gradient(to bottom, #eae0c2 5%, #ccc2a6 100%);
background-color:#eae0c2;
border-radius:22px;
border:4px solid #706752;
display:inline-block;
cursor:pointer;
color:#505739;
font-family:Arial;
font-size:16px;
font-weight:bold;
padding:11px 22px;
text-decoration:none;
text-shadow:0px 1px 0px #ffffff;
}
.myButton:hover {
background:linear-gradient(to bottom, #ccc2a6 5%, #eae0c2 100%);
background-color:#ccc2a6;
}
.myButton:active {
position:relative;
top:1px;
}
生成的 Button.module.css.d.ts
// This file is automatically generated.
// Please do not change this file!
interface CssExports {
}
export const cssExports: CssExports;
export default cssExports;
我还有一个名为styles.d.ts的cssmodule的类型声明
declare module "*.module.css" {
const classes: { [key: string]: string };
export default classes;
}
虽然 Webpack 似乎确实为 css module生成了一些类型,但对我来说它看起来很奇怪。我想我在 css-modules-typescript-loader 上做错了,我尝试了一堆可用的插件,但一直遇到同样的错误。
这是我在 webpack.config.ts 中配置的内容:
import webpack from "webpack";
const config: webpack.Configuration = {
entry: "./src/index.tsx",
resolve: {
extensions: [".tsx", ".ts", ".js", ".css"],
},
module: {
rules: [
{
test: /\.module.css$/,
use: [
"css-modules-typescript-loader",
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
}
},
]
},
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
],
},
},
},
],
},
配置文件
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"target": "ES5",
"plugins": [
{
"name": "typescript-plugin-css-modules"
}
]
},
"include": [
"src"
],
}