2017-03-27 47 views
5

我只是想用fs.readFileSync来读取文件,虽然看起来不能找到它。在打字稿中使用fs

我确信声明一下,我的构造函数中添加它:

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。在打字稿中是否包含fs的特殊方法?

+2

这个你的'Login'组件是一个浏览器组件,对吧?你为什么试图使用'fs'模块? – Diullei

+0

如果您使用wepback,您可以使用'raw-loader'来请求文件内容。 –

回答

16

首先。我无法想象任何在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/**/*" 
    ] 
} 
+1

在我的情况下,'''fs''用于打开一个包含Auth0公钥的文件,该公钥用于验证一个jwt令牌。对于React,我还是比较新的,感谢您的建议! –