Use fs in typescript

前端 未结 2 841
醉酒成梦
醉酒成梦 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:11

    Using node -v 10.15.0 and @types/node:

    It seems declaration has been rewritten...

    fs definition is declared as a module so you should do:

    import fs from "fs"; // Without star

    compiled:

    var fs_1 = __importDefault(require("fs"));

    or

    const fs = require("fs"); instead of require("fs").default;

    with star you will have fs.default.TheFunctionYouWant instead of fs.TheFunctionYouWant

    The better way is to console.log(fs); to see what it is imported.

    {
      "compilerOptions": {
        "typeRoots": [],
        "types": [
          "node"
        ]
      }
    }
    
    0 讨论(0)
  • 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/**/*"
        ]
    }
    
    0 讨论(0)
提交回复
热议问题