我只是想使用 fs.readFileSync
读取文件,但似乎找不到。
我确保声明它,将它添加到我的构造函数中:
export default class Login extends React.Component<LoginProps, {}> {
private webAuth: auth0.WebAuth;
fs: any;
constructor(props: any, context: any) {
super(props, context);
this.fs = require('fs');
this.webAuth = new auth0.WebAuth({
clientID: conf.auth0.clientId,
domain: conf.auth0.domain,
responseType: 'token id_token',
redirectUri: `${window.location.origin}/login`
});
}
[...]
并在一个简单的函数中使用它:
verifyToken = (token) => {
console.log(this.fs);
let contents = this.fs.readFileSync('../utils/public.key', 'utf8');
console.log(contents);
}
但这会引发 Uncaught TypeError: _this.fs.readFileSync is not a function
。有没有一种特殊的方法可以在 Typescript 中包含 fs
?
原文由 Pierre Olivier Tran 发布,翻译遵循 CC BY-SA 4.0 许可协议
我无法想象你会在 React 组件中使用
fs
的任何情况。即使您可以在服务器中使用 React 来渲染内容,相同的代码也应该在客户端中运行,但您无法在客户端中访问fs
。如果您想在 服务器 中使用
fs
,这是一个示例:在您的
package.json
文件上,确保依赖于节点这就是我的
tsconfig.json
文件的样子: