在打字稿中使用 css 模块时出错与 webpack 配置发生反应

Error using css modules in typescript react with webpack config

实际上有一个类似的问题:How do I fix typescript compiler errors on css files?

所以我正在尝试在打字稿中导入 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 时,css 模块似乎没有被导出,我不断收到“[未知] 解析错误:需要声明或声明”:

如何正确导入css模块? 解析错误是否来自我使用的其他包 (eslint/prettier)?

任何提示都会有所帮助,谢谢。

关于打字,您可以通过删除命名空间导入来修复,因为生成的打字现在正在导出默认值。您只需简单地导入为默认导入:

import styles from "./App.css";

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

此外,为了让 css 附加到您的文档中,您可能必须使用 style-loader.

对于解析错误,很有可能与你的linter有关,所以尝试看看你的设置方式。