2017-03-27 58 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,我還是比較新的,感謝您的建議! –