如何解决如何修复CSS文件上的Typescript编译器错误?
我正在尝试使用webpack使用打字稿创建一个React项目。但是我无法使CSS模块正常工作。尝试以打字稿导入CSS文件时,我不断收到此错误:
// postcss.config.js
module.exports = {
plugins: [
require('postcss-import')(),require('postcss-url')(),require('cssnano')({
preset: [
'advanced',{
discardComments: {
removeAllButFirst: true,},reduceIdents: {
gridTemplate: false,autoprefixer: {},],}),};
在我看来,这似乎是webpack期望css文件包含有效的打字稿,但我不确定。我尝试环顾四周,虽然很多人似乎都在努力地同时使用Typescript和CSS模块,但找不到类似问题的人。
我这样导入CSS文件: Button.tsx
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.
这是我要导入的CSS文件。 Button.module.css:
import React from "react";
import "./Button.module.css";
export class Button extends React.Component{
...
}
生成的Button.module.css.d.ts
.myButton {
Box-shadow: 0px 0px 0px -1px #1c1b18;
background:linear-gradient(to bottom,#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;
}
我还为CSS模块提供了一个名为styles.d.ts
的类型声明。// This file is automatically generated.
// Please do not change this file!
interface CssExports {
}
export const cssExports: CssExports;
export default cssExports;
虽然Webpack似乎确实为css模块生成了一些类型,但对我来说却显得很奇怪。我想我在css-modules-typescript-loader中做错了事,我尝试了很多可用的插件,但是却毫无防范地遇到了同样的错误。
declare module "*.module.css" {
const classes: { [key: string]: string };
export default classes;
}
tsconfig.json
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",
解决方法
我有同样的问题。就我而言,这不是webpack的问题。这是打字稿夹板的问题。我通过在.eslintignore文件中添加“ * .css”解决了该问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。