Use fs in typescript

前端 未结 2 862
醉酒成梦
醉酒成梦 2021-01-03 17:45

I\'m just trying to read a file using fs.readFileSync, though it seems it cannot be found.

I made sure to declare it, added it within my constructor:

2条回答
  •  臣服心动
    2021-01-03 18:28

    I can't imagine any case in which you would use fs inside a React component. Even though you can use React in the server to render stuff, the same code is supposed to run in the client, there's no way you can access fs in the client.

    If you want to use fs in the server, this is an example:

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

    On your package.json file, make sure to have a dependency on node

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

    And this is how my tsconfig.json file looks like:

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

提交回复
热议问题