使用 typescript 测试 React 应用程序时出现错误。几个小时后,我意识到错误在于样式的导入方式。我花了几个小时在 gpt 聊天上,但没有多大帮助。当我像这样导入类时:
import * as cls from './Button.module.scss';
concole.log(cls)
返回Module {__esModule: true, Symbol(Symbol.toString Tag): 'Module'}
应用程序中没有错误,但与类相关的测试(玩笑)中有错误。
当我使用时:
import cls from './Button.module.scss';
应用程序中弹出错误:
TypeError: Cannot read properties of undefined (reading 'Button')
at Button (http://localhost:3000/main.28f6bcc41182abdc5bde.js:5916:153)
at renderWithHooks (http://localhost:3000/main.28f6bcc41182abdc5bde.js:23669:18)
at mountIndeterminateComponent (http://localhost:3000/main.28f6bcc41182abdc5bde.js:28281:13)
at beginWork (http://localhost:3000/main.28f6bcc41182abdc5bde.js:29804:16)
at HTMLUnknownElement.callCallback (http://localhost:3000/main.28f6bcc41182abdc5bde.js:12347:14)
at Object.invokeGuardedCallbackDev (http://localhost:3000/main.28f6bcc41182abdc5bde.js:12396:16)
at invokeGuardedCallback (http://localhost:3000/main.28f6bcc41182abdc5bde.js:12460:31)
at beginWork$1 (http://localhost:3000/main.28f6bcc41182abdc5bde.js:35668:7)
at performUnitOfWork (http://localhost:3000/main.28f6bcc41182abdc5bde.js:34774:12)
at workLoopConcurrent (http://localhost:3000/main.28f6bcc41182abdc5bde.js:34760:5)
console.log(cls)
返回 Object,但通过此导入,测试中没有错误。
webpack.config.js:
const cssLoader = {
test: /\.s[ac]ss$/i,
use: [
// Creates style nodes from JS strings
isDev ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: {
auto: (resPath: string) => Boolean(resPath.includes('.module.')),
localIdentName: isDev
? '[path][name]__[local]--[hash:base64:8]'
: '[hash:base64:8]'
}
}
},
"sass-loader",
],
}
我没有对此文件进行任何更改。
全局.d.ts:
declare module '*.scss' {
interface IClassNames {
[className: string]: string
}
const classNames: IClassNames;
export = classNames;
}
这里我尝试用类型替换界面,但实际上设计本身保持不变。
笑话.config.ts:
moduleNameMapper: {
'\\.(s?css)$': 'identity-obj-proxy',
},
在这里我还使用了不同的选项来指定文件扩展名,尽管这些更改没有意义
babel.config.json:
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript",
[
"@babel/preset-react",
{
"runtime": "automatic",
}
]
],
"plugins": [
"i18next-extract"
]
}
我没怎么接触过巴贝尔。
我添加到 Button.tsx 问题 :
import { classNames } from 'shared/lib/classNames/classNames';
import cls from './Button.module.scss';
import { ButtonHTMLAttributes, FC } from 'react';
export enum ThemeButton {
CLEAR = 'clear',
PRIMARY = 'primary'
}
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
className?: string;
theme?: ThemeButton;
}
export const Button: FC<ButtonProps> = (props) => {
const {
className,
children,
theme,
...otherProps
} = props;
return (
<button
type='button'
className={classNames(cls.Button, {}, [className, cls[theme]])}
{...otherProps}
>
{children}
</button>
)
}
我添加到问题 2 Button.module.scss:
.Button {
cursor: pointer;
}
.clear {
padding: 0;
margin: 0;
border: none;
background: none;
outline: none;
}
告诉我如何消除错误并切换到import cls
?