【问题标题】:Error using css modules in typescript react with webpack config在 typescript 中使用 css 模块时出错与 webpack 配置反应
【发布时间】: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)?

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

【问题讨论】:

  • 尝试只使用类名:&lt;h3 className={"background"}&gt;CSS Here&lt;/h3&gt;

标签: css reactjs typescript webpack css-modules


【解决方案1】:

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

import styles from "./App.css";

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

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

对于解析错误,很可能与您的 linter 有关,因此请尝试查看您的设置方式。

【讨论】:

    猜你喜欢
    • 2020-01-13
    • 1970-01-01
    • 2022-07-20
    • 2021-04-15
    • 2021-03-08
    • 2020-01-03
    • 2018-12-24
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多