CSS Modules类型声明后仍触发ESLint类型不安全访问错误
解决TypeScript中SCSS/CSS模块导入后的ESLint类型错误
问题背景
已在index.d.ts中添加两种SCSS/CSS模块的类型声明:
declare module '*.scss' { const value: Record<string, string>; export default value; } declare module '*.css' { const value: Record<string, string>; export default value; }
或
declare module '*.scss' { const value: {[key: string]: string} export default value; } declare module '*.css' { const value: {[key: string]: string} export default value; }
但在TypeScript文件中导入样式模块并访问类名时:
import style from './_fieldset.module.scss'; export const Fieldset: FC<PropChildren> = ({ children }) => ( <fieldset className={style.fieldset}>{children}</fieldset> // 触发ESLint错误 );
出现错误:Unsafe member access .fieldset on an any value.eslint@typescript-eslint/no-unsafe-member-access
解决方案
1. 确保声明文件被TypeScript正确识别
- 检查
index.d.ts的位置是否在tsconfig.json的include范围内,比如在tsconfig.json中配置:
{ "include": ["src/**/*", "index.d.ts"] }
- 确认
tsconfig.json的compilerOptions.moduleResolution为node(默认配置,若被修改需改回)
2. 自动生成精确的样式类型(推荐方案)
手动声明的Record<string, string>是宽泛类型,ESLint可能仍无法准确识别具体类名。使用css-modules-typescript-loader自动为每个样式模块生成包含具体类名的类型文件:
- 安装依赖:
npm install css-modules-typescript-loader --save-dev
- 配置构建工具(以Webpack为例):
module.exports = { module: { rules: [ { test: /\.module\.scss$/, use: [ 'style-loader', { loader: 'css-loader', options: { modules: true } }, 'sass-loader', 'css-modules-typescript-loader' // 添加此loader ] } ] } };
配置后,每次修改.module.scss文件,会自动生成对应的.d.ts文件,例如_fieldset.module.scss.d.ts:
declare const styles: { readonly "fieldset": string; }; export default styles;
此时TypeScript和ESLint都能准确识别style.fieldset的类型,错误自动消失。
3. 临时调整ESLint规则(不推荐长期使用)
若不想自动生成类型文件,可通过以下方式规避错误:
- 类型断言:给导入的样式变量添加明确类型:
import style from './_fieldset.module.scss' as Record<string, string>;
- 修改ESLint规则:在
.eslintrc.json中允许对泛型记录类型的成员访问:
{ "@typescript-eslint/no-unsafe-member-access": ["error", { "allowTypedAccess": true }] }
- 单行忽略:在错误行添加注释临时禁用规则:
<fieldset className={style.fieldset}>{children}</fieldset> // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
内容的提问来源于stack exchange,提问作者Inspiraller
相关产品推荐
相关产品推荐

