TypeScript getting error TS2304: cannot find name ' require'

后端 未结 23 2541
Happy的楠姐
Happy的楠姐 2020-11-22 06:00

I am trying to get my first TypeScript and DefinitelyTyped Node.js application up and running, and running into some errors.

I am getting the error \"TS2304: Cannot

相关标签:
23条回答
  • 2020-11-22 06:46

    I took Peter Varga's answer to add declare var require: any; and made it into a generic solution that works for all .ts files generically by using the preprocess-loader:

    1. install preprocessor-loader:

      npm install preprocessor-loader
      
    2. add the loader to your webpack.config.js (I'm using ts-loader for processing TypeScript sources):

        module: {
            loaders: [{
                test: /\.tsx?$/,
                loader: 'ts-loader!preprocessor?file&config=preprocess-ts.json'
            }]
        }
    
    1. Add the configuration that will add the workaround to every source:
    {
        "line": false,
        "file": true,
        "callbacks": [{
            "fileName": "all",
            "scope": "source",
            "callback": "(function shimRequire(source, fileName) { return 'declare var require: any;' + source; })"
        }]
    }
    

    You can add the more robust require.d.ts the same way, but declare var require: any; was sufficient in my situation.

    Note, there's a bug in preprocessor 1.0.5, which cuts off the last line, so just make sure you have an extra line space return at the end and you'll be fine.

    0 讨论(0)
  • 2020-11-22 06:47

    Just for reference, I am using Angular 7.1.4, TypeScript 3.1.6, and the only thing I need to do is to add this line in tsconfig.json:

        "types": ["node"], // within compilerOptions
    
    0 讨论(0)
  • 2020-11-22 06:47

    I couldn't get the 'require' error to go away by using any of the tricks above.

    But I found out that the issue was that my TypeScript tools for Visual Studio where an old version (1.8.6.0) and the latest version as of today is (2.0.6.0).

    You can download the latest version of the tools from:

    TypeScript for Visual Studio 2015

    0 讨论(0)
  • 2020-11-22 06:50

    Make sure you have installed npm i @types/node

    0 讨论(0)
  • 2020-11-22 06:52

    In my case, it was a super stupid problem, where the src/tsconfig.app.json was overriding the tsconfig.json setting.

    So, I had this in tsconfig.json:

        "types": [
          "node"
        ]
    

    And this one in src/tsconfig.app.json:

        "types": []
    

    I hope someone finds this helpful, as this error was causing me gray hairs.

    0 讨论(0)
提交回复
热议问题