reactjs scss模块的TypeScript定义文件不起作用

qni6mghb  于 2023-06-29  发布在  React
关注(0)|答案(1)|浏览(174)

我刚刚创建了一个React项目使用rollup,下面是我的rollup配置文件:

rollup.config.js

import serve from "rollup-plugin-serve";
import livereload from "rollup-plugin-livereload";
import babel from "@rollup/plugin-babel";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import replace from "@rollup/plugin-replace";
import image from "@rollup/plugin-image";
import postcss from "rollup-plugin-postcss";

const isDevelopment = process.env.NODE_ENV === 'development';

const extensions = [".js", ".jsx", ".ts", ".tsx"];

export default {
  input: isDevelopment ? "src/index.tsx" : "src/index.ts",
  output: [
    {
      file: "dist/iife/bundle.js",
      format: "iife", // for local dev
      sourcemap: true,
    },
    {
      file: "dist/esm/bundle.js",
      format: "esm", // for esm
      sourcemap: true,
    },
  ],
  plugins: [
    image(),
    postcss({
      autoModules: true,
      extensions: [".css", ".scss"],
    }),
    nodeResolve({
      extensions,
    }),
    replace({
      preventAssignment: true,
      "process.env.NODE_ENV": JSON.stringify("development"),
    }),
    commonjs(),
    babel({
      babelHelpers: "bundled",
      extensions,
    }),
    serve({
      open: true,
      verbose: true,
      contentBase: ["", "public"],
      host: "localhost",
      port: 3000,
    }),
    livereload({ watch: "dist" }),
  ],
};

我使用typed-scss-modules包为scss文件生成TypeScript定义文件。

styles.module.scss

.test-test {
  color: red;
}

生成的类型文件如下所示:

styles.module.d.ts

export type Styles = {
  testTest: string;
};

export type ClassNames = keyof Styles;

declare const styles: Styles;

export default styles;

当我在React组件中使用样式时,似乎styles.testTest没有正确传递给dom。

App.tsx

import styles from './styles.module.scss';

const App: React.FC = () => {
  return <div className={styles.testTest} {...restProps}>{children}</div>;
};

div元素接收一个undefined而不是test-test类。有人知道原因吗?

enxuqcxy

enxuqcxy1#

此库仅生成TypeScript定义,类型将在编译后删除。它将不会触及运行时代码。运行时CSS类名仍然是test-test。这就是为什么你得到了undefined
尝试--nameFormat: none选项,默认值为camel
none:不要修改给定的类名

typed-scss-modules ./styles.module.scss --nameFormat none --exportType default

输出:

export type Styles = {
    'test-test': string;
};

export type ClassNames = keyof Styles;

declare const styles: Styles;

export default styles;

className={styles['test-test']}一样使用它

相关问题