Babel typescript unexpected token '?' in statement - javascript

Babel can't transform '?' in statement in typescript.
let t= getObject()?.fieldName;//Module build failed (from ./node_modules/babel-loader/lib/index.js): Unexpected token
let t= getObject() && getObejct().fieldName;

Maybe you can use optional-chaining
npm install --save-dev #babel/plugin-proposal-optional-chaining
add this in your babel file
{
"plugins": ["#babel/plugin-proposal-optional-chaining"]
}

Related

Module not found: Error: Can't resolve 'crypto'

I am getting the following list of errors when I run ng serve.
My package JSON is as follows:
{ "name": "ProName", "version": "0.0.0", "scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e" }, "private": true, "dependencies": {
"#angular-devkit/build-angular": "~0.12.0",
"#angular/animations": "5.2.10",
"#angular/common": "5.2.10",
"#angular/compiler": "5.2.10",
"#angular/compiler-cli": "5.2.10",
"#angular/core": "5.2.10",
"#angular/forms": "5.2.10",
"#angular/platform-browser": "5.2.10",
"#angular/platform-browser-dynamic": "5.2.10",
"#angular/router": "5.2.10",
"#types/dotenv": "^4.0.3",
"#types/errorhandler": "0.0.32",
"#types/express": "^4.16.0",
"#types/node": "^10.5.1",
"apostille-library": "^7.1.0",
"core-js": "^2.5.4",
"dotenv": "^6.0.0",
"errorhandler": "^1.5.0",
"express": "^4.16.0",
"nem2-sdk": "^0.9.7",
"rxjs": "~6.3.3",
"stream": "0.0.2",
"tslib": "^1.9.0",
"typescript": "^2.9.2",
"zone.js": "~0.8.26" } }
The error I get :
ERROR in ./node_modules/aws-sign2/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/aws-sign2' ERROR in
./node_modules/aws4/aws4.js Module not found: Error: Can't resolve
'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/aws4'
ERROR in ./node_modules/ecc-jsbn/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/ecc-jsbn' ERROR in
./node_modules/http-signature/lib/verify.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/http-signature/lib/signer.js Module not found:
Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/nem-sdk/build/external/nacl-fast.js Module not
found: Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/nem-sdk/build/external'
ERROR in ./node_modules/nem-sdk/node_modules/aws-sign2/index.js
I ran into a similar issue lately while trying to use another library (tiff.js) in a small project I was experimenting with.
The way I got around this was to add the following to my package.json file, right after the devDependencies section.
"devDependencies": {
...
},
"browser": {
"crypto": false
}
This didn't seem to have any adverse effect when trying to use the library in the application.
Adding this setting in tsconfig.json file under that project resolve this warning
"compilerOptions": {
"baseUrl": "./",
"paths": {
"crypto": [
"node_modules/crypto-js"
]
}
I like R. Richards's answer, but I thought it would be useful to provide some more information.
This is a known issue with Angular, and the Angular CLI dev team seems to think it's a feature rather than a bug. I, as well as other developers in this issue thread, disagree. Contributors to that thread provided several workaround fixes, but my project didn't compile successfully until I implemented R. Richards' solution. I didn't revert the previous changes, though, so tacnoman's and GrandSchtroumpf's fixes may be of use to others.
Some, like clovis1122 here and others in that issue thread, have questioned why a web app would need access to these libraries and why the necessary tasks can't be completed on the server side instead. I can't speak for everyone, but my use case is that, when authenticating a user account, Strapi responds with a JSON Web Token string that must be decoded by the client. Since the necessary library depends on crypto and stream, you won't be able to extract the JWT expiration time unless those dependencies are available.
In case anyone has trouble extrapolating from R. Richards' answer, you'll have to set to false any dependencies that are showing up in "can't resolve x" errors. For example, the critical part of my package.json is:
"browser": {
"crypto": false,
"stream": false
}
I thought I would expand on what Tarique Ahmed wrote in his answer.
I was using an npm module that had the following line in the code:
const crypto = require('crypto');
I couldn't add:
"browser": {
"crypto": false
}
to the package.json because the crypto package had to be part of the build.
It turns out that during the compilation process Angular seems to have decided to install the crypto-browserify package instead of crypto.
Adding the following to the tsconfig.json file instructs the build to use the crypto-browserify library every time that crypto is required. As you can see, I had the same issue for the stream package.
"paths": {
"crypto": [
"node_modules/crypto-browserify"
],
"stream": [
"node_modules/stream-browserify"
]
}
After having the same issue with Angular 11 and crypto-js 4 (and manually setting the path in tsconfig.json), I found rolling back crypto-js to version 3.1.9-1 fixed the issue. It seems a change made in version 4 caused the issue.
npm install crypto-js#3.1.9-1
Explained here in repo issues:
GitHub issue
If you upgraded to Webpack 5, you need to add this to your webpack config file:
resolve: {
fallback: { crypto: false },
},
aws-sign2 is a NodeJS package (and crypto is a NodeJS module), but it looks like you're dealing with a web application. It makes sense that the crypto module is not available in that environment.
Would it be possible to complete what you need to do server-side? Otherwise, you may need to look for another package.
For Laravel Inertia JS project, my solution was:
1- Add dependencies to package.json
"dependencies": {
"crypto-browserify": "3.12.0",
"crypto-random-string": "^3.3.0",
"stream": "^0.0.2"
}
2-In webpack.config.js:
const path = require('path');
module.exports = {
resolve: {
alias: {
'#': path.resolve('resources/js'),
},
fallback: {
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream'),
},
},
};
3-Install, build and run:
npm install && npm run watch
I have resolved my issue using below steps:
Add below to tsconfig.json to resolve crypto warning:
"paths": {
"crypto": [
"node_modules/crypto-js"
]
},
and add below to angular.json
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
],
...
}
My Error
In my Case the import { get } from "express/lib/response" is the culprit, which is automatically added by vs-code.
So, after removing it I solved my issue
When using #Laravel framework with Laravel Mix this is going to be more trick. I spend some hours on this NPM nightmare and found a solid solution.
So, in your webpack.mix.js you find the 'comment'
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
Now just below that comment add the following lines;
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.LoaderOptionsPlugin({
exports: {
resolve: {
fallback: {
crypto: require.resolve('crypto-browserify'),
}
}
}
})
]
};
});
Now you can use Laravel Mix just like you would edit webpack.config.js ;)
Also; In package.json remove:
--no-progress --hide-modules
These are no longer valid for WebPack >= 5. Enjoy!
After a deep a research i found that the solution is very simple: replace
import * as CryptoJS from 'crypto-js'; with declare var CryptoJS;
Using direct import may not work with ES6 Enviornment..
This may help you.
$ npm i crypto-js#latest // For using latest version 4
import AES from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import { secretKey } from './environments/environment';
/** Encryption */
const data = {key: 'Test Value'};
const ciphertext = AES.encrypt(JSON.stringify(data), secretKey).toString();
console.log('Encrypted Data', ciphertext);
/** Decryption */
const bytes = AES.decrypt(ciphertext, secretKey);
const decryptedData = JSON.parse(bytes.toString(Utf8));
console.log('Decrypted Data', decryptedData);
https://github.com/brix/crypto-js/issues/168#issuecomment-785617218
Add the option allowedCommonJsDependencies with literal "crypto-js" in a array, this in file angular.json:
"architect":
"build": {
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
]
},
}
}
This will disable all warnings, tested in Angular 11.
My problem was that I was trying to build to node and web using the same code, but is not possible to built to web while importing a WebSocket dependency, ws in my case
So the solution is by using a wrapper:
Install a wrapper, I will use isomorphic-ws because is made for ws
npm i --save isomorphic-ws
Remove const WebSocket = require('ws')
Replace with:
const WebSocket = require('isomorphic-ws')
I ended up going into
node_modules/react-scripts/config/webpack.config.js
and adding:
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
https: require.resolve("https-browserify"),
http: require.resolve("stream-http"),
url : require.resolve("url")
}
And now my react app builds with errors but no dependency issues. Ill update this when I get it building.
Add
npm install crypto-js
Or Add a specific version according to your project need
npm install crypto-js#4.0.0
Also, run the above commands in Window "run as administrator" or in Linux use sudo
Alot of answers already but still none of them works. In my case I see warning message
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }' - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "crypto": false }
comment from #stewii did helped me to resolved this.
There is now an ES modules version called "crypto-es". It clears these warnings. npmjs.com/package/crypto-es
After this I imported cryptoES
import CryptoES from 'crypto-es';
and remove the existing import of cryptoJs. Re-start the compile and Voila.. The warning message is gone.
I tried a lot of the solutions above but the final thing that worked for me was downloading the crypto-es package and adding, "type":"module" to package.json.
https://www.npmjs.com/package/crypto-es
I was facing same issue, Just run node patch.js and it worked. The issue is, browser doesn't allow server files to be run on browser. In case you need some of these, You can use node patch.js. If you don't want to run any server file on browser, you can simply apply above mentioned solution by #R.Richards. Might be helpful for someone..
In my case, the solution described by R.Richards doesn't work.
However, following several threads along this issue, I finally understood where to insert the recommendation provided in the warning message and solved this warning.
WARNING in ./node_modules/bcryptjs/dist/bcrypt.js 64:13-45
Module not found: Error: Can't resolve 'crypto' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\bcryptjs\dist'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
**If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }**
Differently from many contributors, I didn't want to install crypto-browserify as I don't need it (*), and I chose to add the fallback { "crypto": false }.
However I didn't know where to add this fallback. After reading several threads, I found it was in the webpack.config.js file, which is located in the directory node_modules/react_scripts/config.
Adding this fallback made the compilation succeed without any warning.
(*) PS : I once tried to add the following fallback { "crypto": require.resolve("crypto-browserify") }, but it led to generation of 7 errors, requiring other modules :
Failed to compile.
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/cipher-base/index.js 2:16-43
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/readable-stream/lib/_stream_readable.js 43:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/_stream_writable.js 65:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/internal/streams/buffer_list.js 63:15-32
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib\internal\streams'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/ripemd160/index.js 3:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\ripemd160'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safe-buffer/index.js 3:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safe-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safer-buffer/safer.js 5:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safer-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
webpack compiled with 7 errors
I had this problem in ReactJS with create-react-app(facebook)
Solution:
First install the necessary packages "crypto-browserify"
Modify webpack.config.js in reactjs with create-react-app this file is inside:
node_modules/react-scripts/config/webpack.config.js
Search module.exports and inside this function there is a return:
module.exports = function (webpackEnv) {
...
return {
...
resolve: {
...
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
}
}
}
}
Note: Is possible you need other packages how "stream-browserify" the steps are same. This solution works, but when the webpack project starts it shows warnings
Pd: I am not native speaker English, but I hope understand me.

JavaScript export / import doesn't work

it might be a silly question but I can't fix it anyway. I have a JavaScript file with various functions I'd like to export.
export function AddNumbers(...numbers)
{
let value = 0;
for(var i = 0;i < numbers.length;i++)
{
value += numbers[i];
}
return value;
}
When I call this method (using mocha) I get an error message "export function AddNumbers(...numbers) Unexpected token export". The project is build as ES6. Does anybody know what I'm doing wrong?
Best regards,
Torsten
You need to use module.exports as NodeJS uses CommonJS Module syntax which requires to use module.exports and not just export which is defined by ES6 module syntax. So, make sure CommonJS is also configured properly in your project.
Another solution is to use Babel. Install it with
npm install babel-core --save-dev
npm install babel-preset-es2015 --save-dev
Create in root directory a file .babelrc with following content
{
"preset" : ["es2015"]
}
and finally change the script in package.json to run into:
"scripts": {
"test": "mocha Tests --require babel-core/register"
}
and now export / import works.

spread syntax doesn't work with node 6.10

i am playing with spread syntax on node/browser.
console.log([{ name: "herry" }, { age: "10" }].reduce((acc, cur) => ({...cur,...acc})))
1) with nodejs v6.10,
SyntaxError: Unexpected token ...
2) Chrome 50
SyntaxError: Unexpected token ...
3) babel stage-0, it's working well.
I am just wandering why it's not working on node 6.10 since it's all green for spread op.
http://node.green/
To get this working:
yarn add -D babel-plugin-transform-object-rest-spread # (or the npm equivalent)
Then add "transform-object-rest-spread" to your .babelrc plugins e.g.
{
"presets": ["es2015"],
"plugins": ["transform-object-rest-spread"]
}

SyntaxError: Unexpected token function - Async Await Nodejs

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better.
I have no clue why, the terminal throws up an error when I try to execute the node code.
helloz.js
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ node helloz.js
/Users/bozzmob/Documents/work/nextgennms/rest/helloz.js:1
(function (exports, require, module, __filename, __dirname) { (async function testingAsyncAwait() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:456:3
BOZZMOB-M-T0HZ:rest bozzmob$ node -v
v6.2.1
What am I missing? Please throw me some light on the same.
Update 1:
I tried to use Babel as Quentin suggested, But, I am getting the following error still.
Updated Code-
require("babel-core/register");
require("babel-polyfill");
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ babel helloz.js > helloz.trans.js
SyntaxError: helloz.js: Unexpected token (3:7)
1 | require("babel-polyfill");
2 |
> 3 | (async function testingAsyncAwait() {
| ^
4 | await console.log("Print me!");
5 | })();
Async functions are not supported by Node versions older than version 7.6.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
That said, versions of Node.js which don’t support async functions are now all past End Of Life and are unsupported, so if you are using an earlier version you should very strongly consider upgrading.
Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html
Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Babel.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();
If you are just experimenting you can use babel-node command line tool to try out the new JavaScript features
Install babel-cli into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
babel-node sample code : https://github.com/stujo/javascript-async-await/tree/15abac
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
Full webpack example : https://github.com/stujo/javascript-async-await
node v6.6.0
If you just use in development. You can do this:
npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev
the package.json would be like this:
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-transform-async-to-generator": "^6.16.0",
"babel-polyfill": "^6.20.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator"]
}
and then, run your async/await script like this:
./node_modules/.bin/babel-node script.js
Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:
npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev
the package.json would be like this:
"devDependencies": {
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-runtime": "6.23.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
and then happy coding with async/await
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json

How to use Typescript with native ES6 Promises

I'm a complete beginner to Typescript and am wondering if it's possible to use ES6 promises in Typescript and what I would have to do to get them to work. I'm running node 0.11.14 and am getting an error during compilation "Cannot find name 'Promise'"
The current lib.d.ts doesn't have promises in it defined so you need a extra definition file for it that is why you are getting compilation errors.
You could for example use (like #elclanrs says) use the es6-promise package with the definition file from DefinitelyTyped: es6-promise definition
You can then use it like this:
var p = new Promise<string>((resolve, reject) => {
resolve('a string');
});
edit You can use it without a definition when targeting ES6 (with the TypeScript compiler) - Note you still require the Promise to exists in the runtime ofcourse (so it won't work in old browsers :))
Add/Edit the following to your tsconfig.json :
"compilerOptions": {
"target": "ES6"
}
edit 2
When TypeScript 2.0 will come out things will change a bit (though above still works) but definition files can be installed directly with npm like below:
npm install --save #types/es6-promise - source
edit3
Updating answer with more info for using the types.
Create a package.json file with only { } as the content (if you don't have a package.json already.
Call npm install --save #types/es6-promise and tsc --init. The first npm install command will change your package.json to include the es6-promise as a dependency. tsc --init will create a tsconfig.json file for you.
You can now use the promise in your typescript file var x: Promise<any>;.
Execute tsc -p . to compile your project. You should have no errors.
Alternative #1
Use the target and lib compiler options to compile directly to es5 without needing to install the es6-shim. (Tested with TypeScript 2.1.4).
In the lib section, use either es2016 or es2015.promise.
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"es2015.promise",
"dom"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
Alternative #2
Use NPM to install the es6-shim from the types organization.
npm install #types/es6-shim --save-dev
Alternative #3
Before TypeScript 2.0, use typings to install the es6-shim globally from DefinitelyTyped.
npm install typings --global --save-dev
typings install dt~es6-shim --global --save-dev
The typings option uses npm to install typings globally and then uses typings to install the shim. The dt~ prefix means to download the shim from DefinitelyTyped. The --global option means that the shim's types will be available throughout the project.
See also
https://github.com/Microsoft/TypeScript/issues/7788 - Cannot find name 'Promise' & Cannot find name 'require'
As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
This will include the promise declarations that comes with TypeScript without having to set the target to ES6.
If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:
tsc a.ts --target es6 --module commonjs
More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options
If you use tsconfig.json, then like this:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6"
}
}
More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json
This the most recent way to do this, the above answer is outdated:
typings install --global es6-promise
Using native ES6 Promises with Typescript in Visual Studio 2015 + Node.js tools 1.2
No npm install required as ES6 Promises is native.
Node.js project -> Properties -> Typescript Build tab
ECMAScript version = ECMAScript6
import http = require('http');
import fs = require('fs');
function findFolderAsync(directory : string): Promise<string> {
let p = new Promise<string>(function (resolve, reject) {
fs.stat(directory, function (err, stats) {
//Check if error defined and the error code is "not exists"
if (err && err.code === "ENOENT") {
reject("Directory does not exist");
}
else {
resolve("Directory exists");
}
});
});
return p;
}
findFolderAsync("myFolder").then(
function (msg : string) {
console.log("Promise resolved as " + msg);
},
function (msg : string) {
console.log("Promise rejected as " + msg);
}
);
A. If using "target": "es5" and TypeScript version below 2.0:
typings install es6-promise --save --global --source dt
B. If using "target": "es5" and TypeScript version 2.0 or higer:
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
C. If using "target": "es6", there's no need to do anything.
I had to downgrade #types/core-js to 9.36 to get it to work with "target": "es5" set in my tsconfig.
"#types/core-js": "0.9.36",
typeorm problems
in tsconfig.json, add the following property : "strictPropertyInitialization": false

Categories