I have the following simple NodeJS code:
const express = require('express');
const server: express.Application = express();
I'm adding Typescript to my project and am new to it so forgive me. With the above code I get the following issues/errors:
For the require:
var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.
For the express.Application usage:
Cannot find namespace 'express'.
If I switch the 'require' to 'import' it fixes the namespace error but is no longer valid Node code so doesn't run (throws a new error about unexpected token for the import).
What's the correct way to write Node code like this with Typescript to avoid these errors?
My tsconfig.json looks like this:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"alwaysStrict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"jsx": "preserve",
"lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": true,
"resolveJsonModule": true,
"sourceMap": true,
"strict": true,
"target": "esnext",
},
"exclude": ["node_modules"],
}
To solve the "Cannot find namespace context" error in React typescript, use a . tsx extension for the files in which you use JSX, set jsx to react-jsx in your tsconfig. json file and make sure to install all of the necessary @types packages for your application.
In TypeScript, you can use namespaces to organize your code. Previously known as internal modules, namespaces in TypeScript are based on an early draft of the ECMAScript modules.
We can create a namespace by using the namespace keyword followed by the namespace_name. All the interfaces, classes, functions, and variables can be defined in the curly braces{} by using the export keyword. The export keyword makes each component accessible to outside the namespaces.
To use it, it must be included using triple slash reference syntax e.g. ///<reference path="path to namespace file" /> . Must import it first in order to use it elsewhere. Compile using the --outFile command. Compile using the --module command.
In case you are a React dev that ends up here as I did - if there is JSX syntax in the file, try changing the extension of the file from .ts
to .tsx
.
After a lot of wasted time, it turns out this was due to the module
setting in the tsconfig file which should be:
"module": "commonjs"
This means Typescript will output common js modules instead of ES6 modules, meaning the code will run correctly as NodeJS code. I was therefore able to change require to import, since it compiles.
Maybe you have to use import instead of require:
import * as express from 'express';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With