【发布时间】:2021-02-18 06:51:33
【问题描述】:
实际上有一个类似的问题:How do I fix typescript compiler errors on css files?
所以我尝试在 typescript 中导入 css 模块,如下所示:
import * as styles from "./App.css";
//App.tsx return some jsx:
<h3 className={styles["background"]}>CSS Here</h3>
// ./App.css
.background {
background-color: pink;
}
我已经为 webpack 安装了 css-loader 和 style-loader,另外还安装了 "css-modules-typescript-loader" 包:https://www.npmjs.com/package/css-modules-typescript-loader
“css-modules-typescript-loader”会在下面自动生成一个新文件:
// /App.css.d.ts
interface CssExports {
'background': string;
}
export const cssExports: CssExports;
export default cssExports;
这是我的 webpack.config.ts:
import * as path from "path";
import * as webpack from "webpack";
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
const config: webpack.Configuration = {
entry: "./src/index.tsx",
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
],
},
},
},
{
test: /\.css$/,
use: [
"css-modules-typescript-loader",
{
loader: "css-loader",
options: {
modules: true,
},
},
],
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js",
},
devServer: {
contentBase: path.join(__dirname, "build"),
compress: true,
port: 4000,
},
plugins: [
new ForkTsCheckerWebpackPlugin({
async: false,
eslint: {
files: "./src/**/*",
},
}),
],
};
export default config;
问题是当我 npm start 时,css 模块似乎没有被导出,并且我不断收到“[unknown] Parsing error: Declaration or statement expected”:
如何正确导入 css 模块? 解析错误是否来自我使用的其他包(eslint/prettier)?
任何提示都会有所帮助,谢谢。
【问题讨论】:
-
尝试只使用类名:
<h3 className={"background"}>CSS Here</h3>
标签: css reactjs typescript webpack css-modules