TypeScript getting error TS2304: cannot find name ' require'

后端 未结 23 3168
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.

提交回复
热议问题