1
votes

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":

enter image description here

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.

1
try use just class name: <h3 className={"background"}>CSS Here</h3>Marbin274

1 Answers

0
votes

Regarding to the typing, you can fix by removing namespace import since generated typing is now exporting default value. You just simply import as default import:

import styles from "./App.css";

<h3 className={styles["background"]}>CSS Here</h3>

Plus, in order to have css getting appended in your document, you might have to use style-loader.

For the parsing error, it's most likely related to your linter, so try to have a look the way you set it up.