在打字稿中使用fs

我只是试图读取使用fs.readFileSync文件,但似乎无法find。

我一定要声明它,并在我的构造函数中添加它:

 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` }); } [...] 

并用它在一个简单的function:

 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 。 有没有一种特殊的方式来在打字稿中包含fs

第一。 我无法想象任何情况下,你会在一个React组件中使用fs 。 即使您可以在服务器中使用React来渲染东西,但是相同的代码应该在客户端运行,您无法在客户端访问fs

如果你想在服务器中使用fs ,这是一个例子:

 import * as fs from 'fs'; fs.readFile(path.join(__dirname, '../../client/index.html'), 'utf8', (error, data) => { // ... }) 

在您的package.json文件中,确保对节点具有依赖性

 "dependencies": { "@types/node": "^7.0.5" } 

这就是我的tsconfig.json文件的样子:

 { "compilerOptions": { "outDir": "./dist/", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es5", "jsx": "react", "allowJs": true, "typeRoots": [ "./node_modules/@types" ] }, "include": [ "./db/**/*", "./src/**/*" ] }