Node error: SyntaxError: Unexpected token import - node.js

I don't understand what is wrong. I checked other forum talking about transpilation and babel. What do I have to do?
node -v
v5.5.0
my code:
import recast from 'recastai'
and the error
(function (exports, require, module, __filename, __dirname) { import recast from 'module1'
^^^^^^
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
at node.js:999:3

ES6 imports are a recently introduced feature and the current stable version of Node does not support them yet. Node.js issue tracker has an open issue for this - but until V8 and Node add support for this feature, you will need to use a transpiler (most popular one being babel) to be able to use imports.
For quickly trying out transpilation, babel provides a web based REPL. This one demonstrates your code being transpiled.
The babel project homepage points to the relevant resources for getting started with Babel and integrating it with your development workflow.
For the simplest setup, visit this setup page and select CLI in the Babel built-ins section.
This basically involves three simple steps:
Install babel-cli : npm install --save-dev babel-cli babel-preset-es2015
Create .babelrc configuration file: echo '{ "presets": ["es2015"] }' > .babelrc
Use the installed module to transpile your source code: ./node_modules/.bin/babel src -d lib
The aforementioned setup page also illustrates how to add an npm script to simplify the last step. Alternatively you can integrate babel with your editor or build chain so that your files are automatically compiled on change.

In case you don't want to deal with babel. This one worked for me.
const calc = require('./my_calc');
let {add, multiply} = calc;

1) Install the latest presets
yarn add --dev babel-preset-latest
2) Create .babelrc and add the following
{
"presets": ["latest"]
}
3) Run your script
npx babel-node yourscript.js
Or in your package.json file add
"scripts": {
"start": "babel-node index.js"
}

Getting Started
First we'll install babel-cli.
$ npm install --save-dev babel-cli
Along with some presets.
$ npm install --save-dev babel-preset-es2015 babel-preset-stage-2
package.json:
"scripts": {
"start": "babel-node index.js --presets es2015,stage-2"
}
run:
$ npm start
Watching file changes with nodemon:
We can improve our npm start script with nodemon.
$ npm install --save-dev nodemon
Then we can update our npm start script.
package.json:
"scripts": {
"start": "nodemon index.js --exec babel-node --presets es2015,stage-2"
}
run:
$ npm start
If you are using pm2, then follow these steps:
$ pm2 start app.js --interpreter babel-node

Its very simple to resolve this issue, import is ES6 syntax and Node has difficulty in supporting it, you need to add Babel as a transpiler, go to package.json and add the following
First add a script tag to use babel while running the JS code for transpiling.
"scripts": {
"start": "nodemon ./app.js --exec babel-node -e js"
}
And then add the following as the Babel devDependencies
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1"
}
after this you also need to configure the babel presets file, therefore create .babelrc file at the root directory and define the presets as follows
{
"presets": [
"es2015",
"stage-0"
]
}
Don't forget to do an npm install in the end

Thanks to a NodeJS enhancement proposal we have a path forward. You can use #standard-things/esm
Find the announcement here Simply run
npm i --save #std/esm
In your packaged today.

Related

How can i use es6 modules in node.js

I'm trying to import express into my project using ES6 syntax, but it keeps giving me the error:
import express from "express";
SyntaxError: Unexpected identifier
I have done a bit of research and found where people were saying to add:
"type":"module"
to my package.json file, which I have done:
...
"description": "Shopping list to learn the MERN stack",
"type": "module",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server.js"
},
...
But I'm still getting the same issue. I would prefer to use the import ES6 syntax rather than this syntax.
const express = require('express')
Solution:
For me the best, easiest and most compatible way to resolve (dated to September 2019) was to:
npm install esm
ensure that the script is run by node with the -r esm option.
Simple as that.
The Node way:
(according to the ECMAScript Modules Documentation)
Other than the "type": "module" property into package.json NodeJS requires the scripts to be run via node --experimental-modules <your_script.js>.
Code into either .mjs or .js extension files will be treated with the support for new ES6. Renaming that I find pretty inconvenient.
Note: "type": "module" is particularly important for supporting .js files. Read the linked documentation.
The solution provided by NodeJS with the --experimental-modules flag didn't work for me in all cases. 🤷‍♂️
Adding the esm packages is more maintainable; and reliable. And can be easily/quickly removed once the ESM support won't be experimental anymore.
Offtopic tip:
If you want to run tests on your ES6 import/export code, I suggest to rely on a solid/flexible framework, like Mocha.
You can follow this instructions to run Mocha tests supporting ES6.
Trying with Jest I wasn't able to run test successfully. Apparently they don't want to directly support the experimental ES6 and suggest to transpile the code (thing that I hate).
References:
https://alxgbsn.co.uk/2019/02/22/testing-native-es-modules-mocha-esm/
https://timonweb.com/tutorials/how-to-enable-ecmascript-6-imports-in-nodejs/
https://nodejs.org/api/esm.html#esm_ecmascript_modules
If you try to run Node js app with ES6 syntax, you will encounter this kind of error
SyntaxError: Cannot use import statement outside a module
let's fix that
install three main packages
npm install --save-dev #babel/core #babel/preset-env #babel/node
npm install --save-dev nodemon
add .babelrc file with this
{ "presets": ["#babel/preset-env"] }
and this in package.json
"start": "nodemon --exec babel-node app.js"
Ok, so, after doing even more research on the ES6 way, this is what worked for me. It's a combination of an answer above and the following:
package.json
node --experimental-modules server.mjs
server.mjs
import dotenv from 'dotenv'
dotenv.config()
const db = process.env.MONGO_URI
I've created a nodejs boilerplate supporting es6 module.
https://github.com/jasonjin220/es6-express-rest-api-boilerplate
You need Babel transpiler to do this, as Node.js doesn't support es6.
First add these packages to your project :
npm install --save-dev babel-cli babel-preset-es2015 rimraf
Then, create a .babelrc file , this is used by Babel transpiler to know some information during transpilation.
touch .babelrc
Then, add this line to .babelrc :
{
"presets": ["es2015"]
}
This tells your Babel to use es6 presets as per 2015 standard.
Then, modify the package.json and tell it to use transpiler.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rimraf dist/ && babel ./ --out-dir dist/ --ignore ./node_modules,./.babelrc,./package.json,./npm-debug.log --copy-files",
"start": "npm run build && node dist/index.js"
},
You have to add the following to script section, this line tells when you run npm run start , the transpiler will first convert the es6 syntax to minmal JavaScript one, later that is used.
Check your dependencies :
"dependencies": {
"express": "^4.15.2",
"morgan": "^1.8.1",
"rimraf": "^2.6.1"
}
And Dev dependencies :
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-preset-es2015": "^6.24.0"
}
This should work, comment if there is any issue.
You need to use Babel,
npm install --save-dev #babel/plugin-proposal-class-properties
then for usage create a .babelrc file if you don't have it, with options:
{"plugins": ["#babel/plugin-proposal-class-properties"]}
then ad devDependencies in package.json
"#babel/plugin-proposal-class-properties": "^7.5.5",
that should do the job.

Errors installing jest in console [duplicate]

I have a test file like so: (I am using create-react-app)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Calculator';
import { getAction, getResult } from './actions/'
import {shallow} from 'enzyme';
import toJson from 'enzyme-to-json';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
it('renders without crashing', () => {
const wrapper = shallow(<App />)
expect(toJson(wrapper)).toMatchSnapshot();
});
it('displays the choosen operator', () => {
const action = {
type: 'GET_ACTION',
operator: '+'
};
expect(getAction("+")).toEqual(action)
})
it('displays the typed digit', () => {
const action = {
type: 'GET_RESULT',
n: 3
};
expect(getResult(3)).toEqual(action);
})
it('checks that the clickevent for getNumber is called',() => {
const clickEvent = jest.fn();
const p = shallow(<p data-n="1" onClick={clickEvent}>1</p>)
p.simulate('click')
expect(clickEvent).toBeCalled();
})
and a package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
// "test": "react-scripts test --env=jsdom",
"test": "jest",
"eject": "react-scripts eject"
},
"devDependencies": {
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.3",
"jest": "^22.4.3"
}
}
when I run jest --updateSnapshot I get:
command not found: jest
but jest is installed.
Jest is installed, but is likely in your ./node_modules/.bin directory. You can append that to your command ./node_modules/.bin/jest --updateSnapshot. Since you already have jest as a scripts command in your package.json you can also run it with npm test -- --updateSnapshot. npm automatically adds ./node_modules/.bin to your path.
update: Newer versions of yarn will resolve node module bin scripts, so you can also just run yarn jest {cmd} and it should work.
I ran into similar issue. I fixed it by installing jest globally.
npm install -g jest
You need to run it this way :
./node_modules/.bin/jest
or run npm test
Install the Jest command-line interface (Jest CLI):
npm install --save-dev jest-cli
Then run the jest command. Working for me in a linux instance by docker on Windows 10.
I was getting zsh: command not found: jest after installing jest and trying to use the command jest. The solution that worked for me was running npx jest
A way to solve the error is to use the "npx" command.
npx jest --version
npx jest --init
In my case, npm didn't install the jest command for some reason.
To fix this:
I deleted the node_modules/jest directory
Re-ran npm install and got the jest command installed.
try using the command
npx jest <folder>
I ran into the same problem. I tried multiple solutions and this worked.
I also have jest CLI installed
you can install it by using this command in your shell
npm install --save-dev jest-cli
just use command
npm test or npm t
Removing node_modules and running npm install again fixed this for me
Also the "new" npm ci command can fix this as it deletes (or clears) node modules and performs a clean install each time, plus it's faster compared to manually deleting node_modules and re-installing
My situation was caused by my git pipeline. I wasn't caching node_modules nor was I caching untracked files.
Ultimately I added
cache:
# untracked: true
key:
files:
- package-lock.json
paths:
- node_modules
to my pipeline .yml and violá
Note
you can either use path OR untracked, find out more about each to see what works best for you
Just reload your bash config file after install jest:
source ~/.bashrc # on linux ?
source ~/.bash_profile # on macOs
Jest will be not recognized but executed with npx jest automatically
I use yarn. Adding jest and jest-cli to node_modules did not make any difference with my attempts to run tests like jest mytest.test.js. In addition to mentioned steps, the following helped to get it running:
yarn jest mytest.test.js
you can run ln -s ./node_modules/.bin/jest jest
and then run jest --init it will work. Or you can install jest cli with npm install --save-dev jest-cli and then run jest --init it will also work.
In my case, I was trying to install jest with yarn on a pipeline to run tests and since I had jest installed as a devDependency it wasn't installing on yarn install.
I found this bug on GitHub https://github.com/yarnpkg/yarn/issues/2739 that it seems that Yarn will not install devDependencies when NODE_ENV=production.
I just needed to change the NODE_ENV and after that, it was working, otherwise, run it like this:
yarn install --production=false
Faced the same issue. But it was due to the wrong node version. If you use the latest jest v29, you need Node version 14 or higher.
You can run the test using npx jest [parameters]. npx is the package runner. It will help you execute a locally installed package.
Had the same issue and was able to solve it by running npm install
Alternatively, just add jest module to package.json dependencies.
{
"dependencies": {
...
"jest": "^29.3.1",
...
}
}

How do I deploy my Typescript Node.js app to Heroku?

When testing locally I was previously running:
"build-live": "nodemon --exec ./node_modules/.bin/ts-node -r dotenv/config -- ./index.ts"
I then figured my Procfile should be something like:
web: ./node_modules/.bin/ts-node -- ./index.ts
But it says module 'typescript' not found, even when it is in package.json. I read in a few places that ts-node is not the way to go to deploy to Heroku, so I am not sure what to do.
UPDATE: I think I am supposed to compile it, so I tried:
web: ./node_modules/.bin/tsc --module commonjs --allowJs --outDir build/ --sourceMap --target es6 index.ts && node build/index.js
This succeeds, however when actually running it, a bunch of the libs I'm using get "Cannot find module '...'".
Alternatively you can have the TypeScript compile as a postinstall hook and run node build/index.js as the only Procfile command:
Your package.json should contain a postinstall hint that gets executed after npm install and before the node process launches:
"scripts": {
"start": "node build/index.js",
"build": "tsc",
"postinstall": "npm run build"
}
You can then leave your Procfile as is:
web: npm start
This 'build on deploy' approach is documented by Heroku here.
The command you've given Heroku is to launch the web "process" by compiling index.ts and dependencies and starting node at index.js. Depending on how things are timed, index.js might or might not exist at the time node starts.
You need to already have your sources compiled by the time you want to start your app. For example, web should just be web: node index.js or similar.
Each build process is different, so you need to figure that out for your own setup. But, suppose you have a classical setup where you push to git and then Heroku picks up that change and updates the app with the new slug. You could just compile things locally and include index.js and any other build output in the repository, for it to be available in the slug for Heroku to use.
A better approach is to use a build server which has an integration with Heroku. After you do the build there, configure it to send the build results to Heroku. Travis has a straighforward setup like this. This way you don't need to include build outputs in your repository, which is considered an anti-pattern.
On a sidenode, try using a tsconfig.json to keep the tsc configuration. It will save you from having to write such long command lines all over the place.
Fabian said that we could do something like:
"scripts": {
"start": "node build/index.js",
"build": "tsc",
"postinstall": "npm run build"
}
As of me writing this, I tested this and can state: postinstall is not required since build script is ran by Heroku. If you want to do it without build script, then you can use heroku-postbuild which will run after dependencies are installed there you run tsc to compile.
My problem was about missing Typescript npm modules. The Typescript compiler tsc was not found when deployed the app to Heroku.
The Heroku deploy process (rightly) does not install development dependencies, in my case the Typescript module was part of devDependencies and thus the tsc command was not running on the Heroku platform.
Solution 1
Add typescript to dependencies: npm i typescript -s
Solution 2
Open Heroku console:
Select console type:
Run the command npm i typescript && npm run tsc
Install typescript as a dev dependency (cf. https://www.typescriptlang.org/download). Once built, your app does not need typescript anymore!
npm install -D typescript
Then in your package.json:
{
"main": "index.js", // <- file will be generated at build time with `tsc`
"scripts": {
"build": "tsc",
"start": "node ."
"start:dev": "ts-node index.ts" // idem, install ts-node as a dev dependency
}
}
The key point here is "build": "tsc".
Why?
Heroku does install all dependencies during build and remove the dev dependencies before the app is deployed (source here).
Node.js deployments will automatically execute an app’s build script during build (since March 11. 2019 source here)
In package.json
"scripts": {
"tsc": "./node_modules/typescript/bin/tsc",
"postinstall": "npm run tsc"
},
Works for me for Heroku deployment.
Installing typescript npm install -D typescript and writing tsc in the build script "build": "tsc", does not work for me. Also, try to run npm i typescript && npm run tsc in the Heroku console which also does not work.
In my case, I remove some dependencies from "devDependencies" to "dependencies", so it goes like this:
"dependencies": {
// The other dependencies goes here, I don't touch them.
// But all TS dependencies I remove to here.
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.2.3",
"ts-loader": "^8.0.18"
},

Babel unexpected token import when running mocha tests

The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.
I have two projects (lets call them A and B) which both use ES6 module syntax. In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error:
SyntaxError: Unexpected token import
Which is preceded by this alleged erroneous line of code from Project B:
(function (exports, require, module, __filename, __dirname) { import
createBrowserHistory from 'history/lib/createBrowserHistory';
The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just fine.
Full Stack Trace:
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Module._extensions..js (module.js:405:10)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (actionCreators.js:4:17)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at /ProjectA/node_modules/mocha/lib/mocha.js:219:27
at Array.forEach (native)
at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14)
at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10)
at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
Here is my test command from package.json:
"test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"
This StackOverflow post is similar but doesn't offer a solution for my use of the command line:
import a module from node_modules with babel but failed
For Babel <6
The easiest way to solve this problem is:
npm install babel-preset-es2015 --save-dev
Add .babelrc to the root of the project with contents:
{
"presets": [ "es2015" ]
}
Ensure that you are running mocha with the "--compilers js:babel-core/register" parameter.
For Babel6/7+
npm install #babel/preset-env --save-dev
Add .babelrc to the root of the project with contents:
{
"presets": [ "#babel/preset-env" ]
}
Ensure that you are running mocha with the --compilers js:babel-register (Babel 6) or --compilers js:#babel/register (Babel 7) parameter
For mocha version 7 or later, use --require babel-register or --require #babel/register respectively.
It seems the only solution is to explicitly include:
require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
in a test helper file, and pass that along to mocha in my test command:
mocha --require ./test/testHelper.js...
The final solution:
Add registerBabel.js: a separate file whose job is to require babel-core/register...
require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
Add an entry.js if your application also relies on babel-node. This acts as a wrapper for your es6 containing application.
require('./registerBabel');
require('./server'); // this file has some es6 imports
You would then run your application with node entry
For mocha testing, testHelper.js should require registerBabel.js as well to initialize babel support at run time.
require('./registerBabel');
And run your mocha tests with mocha --require ./testHelper.js '+(test)/**/*Spec.js'
This will recursively test any file ending in "Spec.js" within "./test". Substitute the pattern with one matching the specs in your project.
Well sure you will have that issue, you are using ES6 that mocha don't know
So you are using babel but you don't use it in your test...
Few Solutions:
A. if you running with NPM use
"test": "mocha --compilers js:babel-core/register test*.js"
B. I'm using
"test": "./node_modules/.bin/mocha --compilers js:babel-core/register **/*spec.jsx"
C. From cli:
mocha --compilers js:babel-core/register test*.js
You can read more at http://www.pauleveritt.org/articles/pylyglot/es6_imports/
I ran into that same issue. Having tried every other solution on stackoverflow and beyond, adding this simple config on package.json did it for me:
"babel": {
"presets": [
"es2015"
]
}
All my ES6 imports worked after that.
By the way, I had this same configuration inside webpack.config.js, but apparently this was the only way to make it work for mocha testing as well.
Hope this helps someone.
I had {"modules": false} in my .babelrc file, like so:
"presets": [
["es2015", {"modules": false}],
"stage-2",
"react"
]
which was throwing
Unexpected token import
Once i removed it, mocha ran successfully.
I had the same issue and fixed it by reading from the babel documentation for integrating Babel with Mocha :
{
"scripts": {
"test": "mocha --compilers js:babel-register"
}
}
For anybody using Babel 7 and Mocha 4, some of the package names have changed a bit and the accepted answer is a bit out-dated. What I had to do was:
npm install #babel/register --saveDev
and adding --require #babel/register to the test line in package.json
"test": "./node_modules/mocha/bin/mocha --require #babel/polyfill --require #babel/register './test/**/*.spec.js'"
The #babel/polyfill fixes some things like async/await functionality if you happen to be using those.
Hope that helps somebody :)
I'm adding another ES6+mocha+babel config answer here, current as of June '19 (refer to dates on answer/commente). mocha has deprecated the --compiler flag, and the version that I'm using has that unavailable even with --no-deprecation flag, c.f. this
Note that I won't include all of the relevant bits from the linked pages, because none of them got me to a clean test build based on the latest versions of mocha and babel; this answer should include the steps that got me to a successful test build.
Following the instructions here, and in this answer, and here, I tried installing what appeared to be the minimum latest babel using npm install:
$ npm install --save-dev mocha
$ npm install --save-dev #babel/preset-env
And I adjusted the mocha invocation in package.json, like so:
"scripts": {
"test": "mocha --compilers js:#babel/register"
}
This led to errors:
Ă— ERROR: --compilers is DEPRECATED and no longer supported.
As above, --no-deprecation didn't help, please reference the page linked above. So following the instructions from here I adjusted package.json:
"scripts": {
"test": "mocha --require js:#babel/register"
}
And started seeing errors about locating babel modules, such as:
Ă— ERROR: Cannot find module '#babel/register'
At this point I started installing babel packages until I could progress. I believe that the full install is something like:
$ npm install --save-dev #babel/preset-env #babel/register #babel/core
The last change required was to update the mocha invocation in package.json, removing the js: prefix, like so:
"scripts": {
"test": "mocha --require #babel/register"
}
I can't answer why this was necessary: if someone can answer this please leave a comment and I'll update my answer with better information.
The last thing that I did was create a .babelrc in the project directory, with the contents:
{
"presets" : ["#babel/preset-env"]
}
I can't recall what prompted this, but I believe that it was because mocha continued to complain about not recognizing the import keyword in my test.js. As above, if someone can answer this please leave a comment and I'll update my answer with better information.
--compilers is deprecated.
My simple solution:
npm install --save-dev babel-core
And in the package.json add your test script like this:
"scripts": {
"test": "mocha --require babel-core/register ./test/**/*.js -r ./test-setup.js"
},
Here's what worked for me. I got a warning when using the --compilers flag.
DeprecationWarning: "--compilers" will be removed in a future version
of Mocha; see https://git.io/vdcSr for more info
I therefore replaced it with the --require flag
"test": "mocha --require babel-core/register --recursive"
Here's my .babelrc:
{
"presets": ["env"]
}
My package.json dev dependencies
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"mocha": "^5.2.0",
}
I found the easiest way to do with with babel 6.X.X was to use nyc and then add in a helper file into the pckage.json
So here is what I used
package.json
{
....
"scripts": {
"test": "nyc mocha --reporter tap 'test/**/*.spec.js'"
},
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-core": "^6.24.0",
"babel-loader": "^6.4.0",
"babel-preset-env": "^1.2.2",
"babel-preset-es2015": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.24.0",
"babel-runtime": "^6.23.0",
"chai": "^3.5.0",
"mocha": "^3.2.0",
"nyc": "^10.1.2",
"webpack": "^2.3.3",
"webpack-config": "^7.0.0",
"webpack-dashboard": "^0.3.0",
"webpack-dev-server": "^2.4.2"
},
"nyc": {
"all": true,
"include": [
"src/**/*.js"
],
"cache": true,
"require": [
"./test/helper/registerBabel.js"
]
}
}
babelrc
{
"presets": [
"es2015", //remove the {modules: false} it doesn't work with this
"stage-2"
]
}
registerBabel.js
/* eslint-disable import/no-commonjs, import/unambiguous */
require('babel-register')();
Now you will be able to use es6 in your tests or wherever you need to. Mine are all failing ;)
Then npm run test which will fire off nyc mocha --reporter tap 'test/**/*.spec.js'
I resolved this issue this morning with the following instructions
Install NPM Modules
npm install --save-dev #babel/polyfill
npm install --save-dev #babel/register
package.json:
"scripts": {
"test": "mocha --require #babel/register --require #babel/polyfill src/DesktopApplication/Tests",
}
.babelrc
{
"presets": ["#babel/env"]
}
I resolved this issue this morning with the following instructions from the official Using Babel instructions for Mocha 4:
Install NPM Modules
npm install --save-dev babel-polyfill
npm install --save-dev babel-preset-env
npm install --save-dev babel-register
or a single command:
npm i -d babel-polyfill babel-preset-env babel-register
package.json:
"scripts": {
"test": "mocha --require babel-polyfill --require babel-register"
}
.babelrc
{
"presets": ["env"]
}
You might need to specify the extensions option if you're using TypeScript:
require("#babel/register")({
extensions: ['.jsx', '.js', '.ts', '.tsx']
})
I installed mocha and met the exact same error when I use import in my code. By doing the following actions, the issue was fixed.
npm install babel-core --save-dev
npm install babel-preset-es2015 --save-dev
npm install babel-preset-stage-0 --save-dev
And then add a .babelrc file:
{
"presets": [
"es2015"
]
}
And then run mocha in this way:
mocha --compilers js:babel-core/register
I had the same problem.
When running tests I realized I actually wanted to stub dependent modules. It's good for unit testing and prevents babel from transforming submodules. So I used proxyquire, namely:
const proxyquire = require('proxyquire').noCallThru()
const myTestedModule = proxyquire('../myTestedModule', {
'dependentModule1': { //stubbed module1 },
'dependentModule2': { //stubbed module2 }
})
for a more future proof setting
npm install babel-preset-latest --save-dev
and in .babelrc
{
"presets": [ "latest" ]
}
as opposed to...
npm install babel-preset-es2015 --save-dev
and
{
"presets": [ "es2015" ]
}

Node - how to run app.js?

I am very new to Node.js and I tried to run a project (made by other developer) by having a command in terminal node app.js. But I encountered below error, do you have any idea how to run this project?
I followed few instructions here to run a project.
Error logs below:
Junryls-Mac-mini:app junrylmaraviles$ node app.js
/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1
(function (exports, require, module, __filename, __dirname) { define('src/app'
^
ReferenceError: define is not defined
at Object.<anonymous> (/Users/junrylmaraviles/Desktop/myfolder/mysubfolder/app/app.js:1:63)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
Assuming I have node and npm properly installed on the machine, I would
Download the code
Navigate to inside the project folder on terminal, where I would hopefully see a package.json file
Do an npm install for installing all the project dependencies
Do an npm install -g nodemon for installing all the project dependencies
Then npm start OR node app.js OR nodemon app.js to get the app running on local host
use nodemon app.js ( nodemon is a utility that will monitor for any changes in your source and automatically restart your server)
The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install then node app.js. This should install dependencies and then start the app.
Just adding this.
In your package.json, if your "main": "index.js" is correctly set. Just use node .
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
...
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
...
},
"devDependencies": {
...
}
}
To run app.js file check "main": "app.js" in your package.json file.
Then run command $ node app.js That should run your app.
Node is complaining because there is no function called define, which your code tries to call on its very first line.
define comes from AMD, which is not used in standard node development.
It is possible that the developer you got your project from used some kind of trickery to use AMD in node. You should ask this person what special steps are necessary to run the code.
To run a node js project you can run the project by below commands
node app.js
But if you want to run your project with npm start then you need to pass "start": "Node app.js" in the scripts of the package.json file
So, your package.json file will look like below
"scripts": { "start": "node app.js", "test": "test" }
Once you are done with the changes then you just need to save the file and then go to the terminal hit the npm start command you will see that the project started as its working on the node app.js command
Refer to below image for clarification
You can also see in the below image that your project runs on both command node app.js as well as npm start
If the Node Js Project :
Normally we can run,
>node app
(or)
Install nodemon dependency (npm i -g nodemon)
>nodemon app.js
(or)
In Package.json, inside the scripts has "start":"nodemon app.js"
>npm start
you have a package.json file that shows the main configuration of your project,
and a lockfile that contains the full details of your project configuration such as the urls that holds each of the package or libraries used in your project at the root folder of the project......
npm is the default package manager for Node.js....
All you need to do is call $ npm install from the terminal in the root directory where you have the package.json and lock file ...since you are not adding any particular package to be install ..... it will go through the lock file and download one after the other, the required packages from their urls written in the lock file if it isnt present in the project enviroment .....
you make sure you edit your package.json file .... to give an entry point to your app..... "name":"app.js" where app.js is the main script .. or index.js depending on the project naming convention...
then you can run..$ Node app.js or $ npm start if your package.json scripts has a start field config as such "scripts": { "start": "Node index.js", "test": "test" }..... which is indirectly still calling your $ Node app.js
in package.json file add the script
"start":"node filename.js"
and run in terminal - > npm start
Node manages dependencies ie; third party code using package.json so that 3rd party modules names and versions can be kept stable for all installs of the project. This also helps keep the file be light-weight as only actual program code is present in the code repository. Whenever repository is cloned, for it to work(as 3rd party modules may be used in the code), you would need to install all dependencies.
Use npm install on CMD within root of the project structure to complete installing all dependencies. This should resolve all dependencies issues if dependencies get properly installed.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Resources