Gatsby:将 SASS 模块与 Typescript 结合使用

Amb*_*ier 3 sass typescript css-modules gatsby

我正在尝试让 typescript 和 sass 模块在 Gatsby 项目中协同工作。

我正在使用gatsby-plugin-ts-loadergatsby-plugin-sass插件。

索引.tsx

import * as React from 'react';
import styles from './index.module.scss'; // TS2307: Cannot find module './index.module.scss'.

export default () => <div  className={styles.root}>
    <h1>Hello Gatsby!</h1>
</div>;

Run Code Online (Sandbox Code Playgroud)

索引.模块.scss

.root {
  h1 {
    color: red;
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误TS2307: Cannot find module './index.module.scss'.。如果我把它放在@ts-ignorescss 导入行之前,我会得到TypeError: index_module_scss_1.default is undefined.

Amb*_*ier 9

  1. 添加。"esModuleInterop": truetsconfig.json
  2. 添加包含内容的文件src/global.d.ts
// necessary to make scss module work. See https://github.com/gatsbyjs/gatsby/issues/8144#issuecomment-438206866
declare module '*.scss' {
    const content: {[className: string]: string};
    export = content;
}
Run Code Online (Sandbox Code Playgroud)
  1. 添加导入import styles from './index.module.scss';
  2. 如果它编译了,并且 css 没有显示,请确保它是正确的,例如混淆.rootroot;)。

来源https://github.com/gatsbyjs/gatsby/issues/8144#issuecomment-438206866