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
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:
install preprocessor-loader:
npm install preprocessor-loader
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'
}]
}
{
"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.
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
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
Make sure you have installed npm i @types/node
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.