There's actually a similar question out there: How do I fix typescript compiler errors on css files?
So I'm trying to import css module in typescript, like this:
import * as styles from "./App.css";
//App.tsx return some jsx:
<h3 className={styles["background"]}>CSS Here</h3>
// ./App.css
.background {
background-color: pink;
}
I've installed css-loader and style-loader for webpack, also additionally "css-modules-typescript-loader" package: https://www.npmjs.com/package/css-modules-typescript-loader
The "css-modules-typescript-loader" will generate a new file below automatically:
// /App.css.d.ts
interface CssExports {
'background': string;
}
export const cssExports: CssExports;
export default cssExports;
And here's my 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;
The thing is when I npm start, the css module doesn't seem to be exported and I keep getting "[unknown] Parsing error: Declaration or statement expected":
How to correctly import the css modules? Could the Parsing error come from some other package I use (eslint/prettier)?
Any hint would be helpful, thank you.
<h3 className={"background"}>CSS Here</h3>
– Marbin274