MongDB cannot find Promise type definition - node.js

I have created a new project, installed few type definitions (from DefinitelyTyped) and made a basic src/go.ts file.
Whenever I transpile the code, I get a ton of TS2304: Cannot find name 'Promise' errors!
The ./typings/mongodb/index.d.ts is referencing the Promise, but the compiler does not seem to find that.
Please note that I have dt~promise installed as well.
Screenshot (Errors on the left side, type definitions installed and the app code are on the right)
Content of typings.json:
{
"globalDependencies": {
"dotenv": "registry:dt/dotenv#2.0.0+20160327131627",
"express": "registry:dt/express#4.0.0+20160708185218",
"express-serve-static-core": "registry:dt/express-serve-static-core#4.0.0+20160805091045",
"mime": "registry:dt/mime#0.0.0+20160316155526",
"mongodb": "registry:dt/mongodb#2.1.0+20160602142941",
"mongoose": "registry:dt/mongoose#4.5.4+20160807120805",
"mongoose-promise": "registry:dt/mongoose-promise#4.5.4+20160720003345",
"node": "registry:dt/node#6.0.0+20160807145350",
"promise": "registry:dt/promise#7.1.1+20160602154553",
"serve-static": "registry:dt/serve-static#0.0.0+20160606155157"
}
}
Any thoughts?

I've experienced the same issue (more or less, using #types instead of typings) and was able to solve it by installing the type definitions for CoreJS.
Screenshots
Apologize for linking to a library, this is my first post so I am unable to provide more than two links per post.
Image explanations:
First screenshot shows similar error, type definition file for MongoDB is unable to find 'Promise'.
Install type definitions for CoreJS. Note that I am getting my type definitions through NPM and not Typings. So to do something similar in Typings you would run something like:
typings install dt~core-js --save --global
Third screenshot shows build command with no errors on output 😁
I hope this resolves your issue.

I had the same issue installing lastest version of mongodb and mongoose typings.
The new definition file for mongodb assumes you are using ES6 promise so if you change the target of the typescript compiler in the tsconfig.json to es6 it should do the trick :
tsconfig.json:
{
"compilerOptions": {
...
"target": "ES6",
...
}
}

For typings: typings install core-js --ambient --save.
It works for me.

Related

React - Module not found: Error: Can't resolve 'fs' in.. and can't resolve 'net' in

new to webpack configurations. I'm getting this error in my app and it doesn't compile. According to countless suggestions from SO, I've tried the setting (or variations of it) in my package.json:
"browser": {
"fs": false,
"net": false
}
And in webpack.config:
node: { fs: 'empty',
net: 'empty' }
It compiles but all it does is it has the file go blank on localhost.
Webpack version: 4.46.0
Node: 16.14.0
Windows 11
Any help greatly appreciated.
Webpack will let you bundle up modules of browser-compatible code into a production bundle for sending to the browser.
The fs and net modules are not browser-compatible code. They depend on APIs which are provided by Node.js and which are not provided by browsers.
Thus attempts to bundle them error, and if you tell webpage to treat them as empty then the generated bundle won't include them.
Make sure you are not importing the following from express or even json or something else
import { response } from 'express'
For anyone who is using React (happened to me in react). I have even read with NextJs this works but haven't tested it.
Man I did everything like config-overrides and node modules webpack config file updates and also changed react-scripts version 5 to 4 but nothing worked. But as soon as I removed response. It worked.
That one line only made me go into 7 hours of debugging mode.
But always enjoy it :)
It took me while to figure it out and I found out that it may be due to incompatible Node-gyp and Node-sass packages.My app is running fine now.
Again, the errors:
"Module not found: Error Can't resolve "fs" in..."
"Module not found: Error Can't resolve "net" in..."
Try this in the following order :
Delete package.lock.json
Update/install these packages to make them compatible with each other.
These versions worked for Node 16.14.0:
"node-sass": "^6.0.0"
"node-gyp": "^7.1.0" (in my case - npm install -g node-gyp#7.1.0)
"sass-loader": "^10.0.0"

TypeScript not finding the types in #types

I am trying to import some types from #types/webgl2 in my project.
I have followed every bit of advice mentioned here:
TypeScript typings give me "index.d.ts is not a module"
Added this to the top: import 'webgl2';
I have made sure "modeResolution" is "true" in tsconfig.json
I added a line "types":["webgl2"] to my tsconfig.json
Added "#types/webgl2": "0.0.4" to both devDependencies and dependencies in package.json.
Did an npm install in my project folder:
npm WARN package.json webgl#0.0.1 No README data
npm WARN package.json Dependency '#types/webgl2' exists in both dependencies and devDependencies, using '#types/webgl2#0.0.4' from dependencies
I can easily see webgl2 in node_modules/#types and I can also see the declaration for all errored symbols under:
declare var WebGl2RenderingContext {
and I still get these errors:
(multiple lines)
Cannot find name 'WebGl2RenderingContext'. Did you mean 'WebGL2RenderingContext'?
Corresoonding to:
const format = WebGl2RenderingContext.RED;
Resolved by fixing spelling mistakes.
In your tsconfig set the typeRoot:
{
"typeRoots": ["node_modules/#types"]
}
For NG9'ers, try, deleting your package-lock.json file, then:
npm i crypto
For me, I had an issue where types was specified in tsconfig so some types weren't automatically added to the global scope.
So the package in question was #types/dom-webcodecs and I added this to tsconfig like this
{
"compilerOptions": {
"types": [
"dom-webcodecs",
...
]
}
}
and after that I could access the types.
This is different than typeRoots which another answer talks about. You can explore the difference here if need be.

Running into "couldn't infer parser" error using vue-cli

I'm getting an error repeatedly when trying to build a new webpack project using vue-cli. I'm following along with the docs on the latest build (3.0.0-beta.11), also tried with an earlier version, which wasn't beta.
When I run yarn serve it attempts to start the dev server and build the project but fails here:
error in ./src/App.vue?vue&type=template&id=7ba5bd90
Module build failed: Error: No parser and no file path given, couldn't infer a parser.
at normalize (/Users/cory/Code/chickadee/my-project/node_modules/prettier/index.js:7051:13)
at formatWithCursor (/Users/cory/Code/chickadee/my-project/node_modules/prettier/index.js:10370:12)
at /Users/cory/Code/chickadee/my-project/node_modules/prettier/index.js:31115:15
at Object.format (/Users/cory/Code/chickadee/my-project/node_modules/prettier/index.js:31134:12)
at actuallyCompile (/Users/cory/Code/chickadee/my-project/node_modules/#vue/component-compiler-utils/dist/compileTemplate.js:93:29)
at compileTemplate (/Users/cory/Code/chickadee/my-project/node_modules/#vue/component-compiler-utils/dist/compileTemplate.js:26:16)
at Object.module.exports (/Users/cory/Code/chickadee/my-project/node_modules/vue-loader/lib/loaders/templateLoader.js:42:20)
# ./src/App.vue?vue&type=template&id=7ba5bd90 1:0-194 1:0-194
# ./src/App.vue
# ./src/main.js
# multi (webpack)-dev-server/client/index.js (webpack)/hot/dev-server.js ./src/main.js
About my setup
Mac OS
I'm running node v8.5.0
packages are installed with yarn
The Things I've Attempted
Different versions of vue-cli to generate a new project. The projects generate and install modules.
Tried removing the prettier module, but the error still seems to come up.
Tried reinstalling all modules.
What else might I try to get past this error?
Removing the current node_modules folder from the project, adding "prettier": "^1.12.1" to package.json and running npm install solved the issue.
Another option is to run npm install prettier#1.12.1 without removeing the node_modules folder before
Update:
For some users, verion 1.12.1 did not work
#Kivin proposed another solution that can be found here: vue webpack template missing parser
Known issue and it will be fixed in the next version of vue-cli
In prettier 1.13.0, default parser was removed with a minor version(used to be babylon)
Issue: https://github.com/vuejs/component-compiler-utils/issues/14
Issue at prettier repo: https://github.com/prettier/prettier/issues/4567
Sorry, we committed the age-old semver sin- we knew this was a breaking change, but because it would only affect a subset of our users, we didn't bump the major version, because we didn't want to create friction for our users to upgrade.
To get the old behavior, add parser: "babylon". You may also want to lock prettier to a specific version in your package.json.
Running npm install prettier#1.12.1 solved it for me. Thanks lsxliron.
Right now, I tried all the options..downloading and updgrading prettier...but none workied. Until I studied what happened carefully.
Apparently, the prettier team removed the default parser which was babylon and in so doing...broke the internet.
Just kidding.
Issue repo
The simplest solution, according to them would be to simply add the parser back.
This has been picked up by the Vue team and its expected to be shipped with the latest fix release.
If you are using Vue Loader/Yarn, dont even bother to try all the suggestions...I tried them all.
What fixed it for me was...go to
node_modules\vue-loader\lib\template-compiler ...open index.js and look for
// prettify render fn
if (!isProduction) {
code = prettier.format(code, { semi: false})
}
and change the lines to:
// prettify render fn
if (!isProduction) {
code = prettier.format(code, { semi: false, parser: 'babylon' })
}
Thats it!
Then once the issue got fixed, everything will just be rolled back and you will still be fine.
Try this...it will save you countless minutes of searches....
As already pointed out by the various resonses, you may need to rollback the version of the prettier package.
in your package.json file, you may need to force npm to use a version (i.e. remove the hat ^)
mine looks something like this
"devDependencies": {
"prettier": "1.12.1",
"typescript": "^2.6.1",
"vue": "^2.5.16",
"vue-styleguidist": "^1.4.4",
"vue-webpack-loaders": "^1.0.6",
"webpack": "^3.1.0"

What's the equivalence of typings globalDevDependencies for npm #types packages?

I want to upgrade an tsc#1.8 project to tsc#2 and in the process ditch typings from my tool chain.
It's not a problem for the common depencies as these dependencies from my typings.json:
"dependencies": {
"bluebird": "registry:npm/bluebird#3.3.4+20160515010139",
"lodash": "registry:npm/lodash#4.0.0+20160416211519",
"mime": "registry:npm/mime#1.3.0+20160423043021"
}
I can easily install via
npm i #types/bluebird #types/lodass #types/mime
Yet I also have some globalDevDependencies for my test setup in my typings.json:
"globalDevDependencies": {
"mocha": "registry:dt/mocha#2.2.5+20160317120654"
}
My first try was:
npm install #types/mocha --save-dev
Yet now tsc complains it doesn't know the mocha functions it and describe.
tests/unit/HelloServiceTest.ts(4,1): error TS2304: Cannot find name 'describe'.
tests/unit/HelloServiceTest.ts(5,5): error TS2304: Cannot find name 'it'.
tests/unit/HelloServiceTest.ts(10,5): error TS2304: Cannot find name 'it'.
As a longshot I mistakenly thought installing those globally might resolve the issue:
npm i #types/mocha -g
I also stumbled across this issue where the solution was to not exclude the types folder in the tsconfig.json:
"exclude": [
"node_modules",
"!node_modules/#types"
]
yet it also didn't work for me, throwing the same error.
In the end, I don't know how to achieve the same effect that typings' globalDevDependencies and globalDependencies had when I want to use just npm and the #types/* packages instead of typings.
This thread pointed me in the right direction, as I have to add the types to the tsconfig.json:
{
"compilerOptions": {
"target": "ES6",
"types": ["node", "mocha", "chai"],
...
}
The types option also have a verbose documentation.

TypeScript getting error TS2304: cannot find name ' require'

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 find name 'require' " when I attempt to transpile a simple TypeScript Node.js page. I have read through several other occurrences of this error on Stack Overflow, and I do not think I have similar issues.
I am running at the shell prompt the command:
tsc movie.server.model.ts.
The contents of this file are:
'use strict';
/// <reference path="typings/tsd.d.ts" />
/* movie.server.model.ts - definition of movie schema */
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var foo = 'test';
The error is thrown on the var mongoose=require('mongoose') line.
The contents of the typings/tsd.d.ts file are:
/// <reference path="node/node.d.ts" />
/// <reference path="requirejs/require.d.ts" />
The .d.ts file references were placed in the appropriate folders and added to typings/tsd.d.ts by the commands:
tsd install node --save
tsd install require --save
The produced .js file seems to work fine, so I could ignore the error. But I would appreciate knowing why this error occurs and what I am doing wrong.
Quick and Dirty
If you just have one file using require, or you're doing this for demo purposes you can define require at the top of your TypeScript file.
declare var require: any
TypeScript 2.x
If you are using TypeScript 2.x you no longer need to have Typings or Definitely Typed installed. Simply install the following package.
npm install #types/node --save-dev
The Future of Declaration Files (6/15/2016)
Tools like Typings and tsd will continue to work, and we’ll be working
alongside those communities to ensure a smooth transition.
Verify or Edit your src/tsconfig.app.json so that it contains the following:
...
"types": [ "node" ],
"typeRoots": [ "../node_modules/#types" ]
...
Make sure is the file in the src folder and no the one on the root app folder.
By default, any package under #types is already included in your build unless you've specified either of these options. Read more
TypeScript 1.x
Using typings (DefinitelyTyped's replacement) you can specify a definition directly from a GitHub repository.
Install typings
npm install typings -g --save-dev
Install the requireJS type definition from DefinitelyType's repo
typings install dt~node --save --global
Webpack
If you are using Webpack as your build tool you can include the Webpack types.
npm install --save-dev #types/webpack-env
Update your tsconfig.json with the following under compilerOptions:
"types": [
"webpack-env"
]
This allows you to do require.ensure and other Webpack specific functions.
Angular CLI
With CLI you can follow the Webpack step above and add the "types" block to your tsconfig.app.json.
Alternatively, you could use the preinstalled node types. Keep in mind this will include additional types to your client-side code that are not really available.
"compilerOptions": {
// other options
"types": [
"node"
]
}
For TypeScript 2.x, there are now two steps:
Install a package that defines require. For example:
npm install #types/node --save-dev
Tell TypeScript to include it globally in tsconfig.json:
{
"compilerOptions": {
"types": ["node"]
}
}
The second step is only important if you need access to globally available functions such as require. For most packages, you should just use the import package from 'package' pattern. There's no need to include every package in the tsconfig.json types array above.
You can
declare var require: any
Or, for more comprehensive support, use DefinitelyTyped's require.d.ts
Also, instead of var mongoose = require('mongoose'), you could try the following
import mongoose from 'mongoose' // or
import mongoose = require('mongoose')
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.
This answer relates to modern setups (TypeScript 2.x, Webpack > 2.x)
You don't need to install #types/node (which is all of Node.js types and is irrelevant for front-end code, actually complicating things such as setTimout different return values, etc..
You do need to install #types/webpack-env
npm i -D #types/webpack-env
which gives the runtime signatures that Webpack has (including require, require.ensure, etc.)
Also make sure that your tsconfig.json file has no set 'types' array -> which will make it pickup all type definitions in your node_modules/#types folder.
If you want to restrict search of types you can set the typeRoot property to node_modules/#types.
Instead of:
'use strict';
/// <reference path="typings/tsd.d.ts" />
Try:
/// <reference path="typings/tsd.d.ts" />
'use strict';
i.e. reference path first.
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 found the solution was to use the TSD command:
tsd install node --save
Which adds/updates the typings/tsd.d.ts file and that file contains all the type definitions that are required for a node application.
At the top of my file, I put a reference to the tsd.d.ts like this:
/// <reference path="../typings/tsd.d.ts" />
The require is defined like this as of January 2016:
declare var require: NodeRequire;
interface NodeModule {
exports: any;
require: NodeRequireFunction;
id: string;
filename: string;
loaded: boolean;
parent: any;
children: any[];
}
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'
}]
}
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.
For me it is resolved by adding types to the angular compiler options.
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"types": [ "node" ]
}
I've yet another answer that builds upon all previous ones that describe npm install #types/node and including node in tsconfig.json / compilerOptions / types.
In my case, I have a base tsConfig.json and a separate one in the Angular application that extends this one:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": []
},
My problem was the empty types in this tsconfi.app.json - it clobbers the one in the base configuration.
import * as mongoose from 'mongoose'
As approved answer didn't mention possibility to actually create your own typings file, and import it there, let me add it below.
Assuming you use npm as your package manager, you can:
npm i #types/node --save-dev
Then in your tsconfig file:
tsconfig.json
"include": ["typings.d.ts"],
Then create your typings file:
typings.d.ts
import 'node/globals'
Done, errors are gone, enjoy TypeScript :)
I've been struggling from this issue as well. I believe that this works for all release candidates aka rc but I didn't test is though. For #angular rc.2 it works well.
Add core-js as npm dependency in package.json
run typings install core-js --save
remove all "es6-shim" occurances in your package.json. You don't need it anymore.
Cheers!
Sometime missing "jasmine" from tsconfig.json may cause this error. (TypeScript 2.X)
So add
"types": [
"node",
"jasmine"
]
to your tsconfig.json file.
Electron + Angular 2/4 addition:
On top of adding the 'node' type to ts.config various files, what eventually worked for me was adding the next to the
typings.d.ts file:
declare var window: Window;
interface Window {
process: any;
require: any;
}
Note that my case is developing with Electron + Angular 2/4. I needed the require on the window global.
Did you specify what module to use to transpile the code?
tsc --target es5 --module commonjs script.ts
You must do that to let the transpiler know that you're compiling NodeJS code. Docs.
You must install mongoose definitions as well
tsd install mongoose --save
Do not use var to declare variables (unless necessary, which is a very rare case), use let instead. Learn more about that
Just in addition to cgatian's answer, for TypeScript 1.x
If you are still seeing errors, please specifically provide index.d.ts in your compiler options.
"files": [
"typings/index.d.ts"
]
Make sure you have installed npm i #types/node
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
If you can compile code, but Visual Studio 2015 marks 'require' functions as errors with error text cannot find name 'require' or cannot resolve symbol 'require', update TypeScript for Visual Studio 2015 to the latest version (at the moment 2.1.5) and update ReSharper (if you use it) to at least version 2016.3.2.
I had this annoying problem for a while and couldn't find a solution, but I finally resolved it this way.
Add the following in tsconfig.json:
"typeRoots": [ "../node_modules/#types" ]
If you are using Yarn v3 and see this error (cannot find name require) or other node related "cannot find" errors in VSCode, make sure you have Yarn's VSCode sdk plugin installed and have selected the workspace version of Typescript.
Command to install the sdks:
yarn dlx #yarnpkg/sdks
To set the Typescript version:
Select a Typescript file
Press Command + Shift + P
Type Typescript: Select Typescript Version
Select "Use Workspace Version"
See https://yarnpkg.com/getting-started/editor-sdks#vscode for more details.
If you are facing this issue in a .ts file which is only there to provide you some constant values, then you can just
rename your .ts file to .js file
and the error will not come again.

Resources