在打字稿中使用 fs

新手上路,请多包涵

我只是想使用 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 许可协议

阅读 301
1 个回答

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

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

 import * as fs from 'fs';
import * as path from 'path';
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/**/*"
    ]
}

原文由 Andre Pena 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题