Babel unexpected token import when running mocha tests - node.js

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" ]
}

Related

Including #firebase/app in firebase functions package.json

After updating to the newest firebase SDK and tools
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
I started getting the following error when trying to deploy my firebase functions:
TypeError: instance.INTERNAL.registerComponent is not a function
at registerDatabase (/Users/jr/projects/docavea/functions/node_modules/#firebase/database/dist/index.node.cjs.js:15168:39)
at Object.<anonymous> (/Users/jr/projects/docavea/functions/node_modules/#firebase/database/dist/index.node.cjs.js:15200:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at FirebaseNamespace.get [as database] (/Users/jr/projects/docavea/functions/node_modules/firebase-admin/lib/firebase-namespace.js:282:38)
I have found posts on https://github.com/firebase/firebase-admin-node/issues/714 and
https://github.com/firebase/firebase-admin-node/issues/717 and https://twitter.com/plane1113/status/1203009025232654336 that suggests various solutions for this problem, but none of them worked for me, except to include #firebase/app. Some suggested that this was cause by having #firebase/app somewhere in my project but when I ran
npm ls #firebase/app I got
functions# /Users/jr/projects/docavea/functions
└── (empty)
So my question is: What is #firebase/app and is it a problem to include it in my firebase functions package.json
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"main": "lib/src/index.js",
"dependencies": {
"#firebase/app": "^0.5.0",
"#sendgrid/mail": "^6.4.0",
"cors": "^2.8.5",
"firebase-admin": "^8.9.0",
"firebase-functions": "^3.3.0",
"lodash": "^4.17.15",
"mailchimp-api-v3": "^1.13.1"
},
"peerDependencies": {
"#google-cloud/firestore": "^3.3.2"
},
"engines": {
"node": "8"
},
"devDependencies": {
"tslint": "^5.20.1",
"typescript": "^3.7.4"
},
"private": true
}
First, to answer the question #firebase/app is a module that is part of the Firebase Web SDK (you get it by npm install firebase) and never needs to be manually installed, and should not be installed at all for firebase-admin.
So in a nutshell, here is what's going on with this error, in general: firebase-admin has a dependency called #firebase/database, which is shared with the Firebase Web SDK. A recent release of #firebase/database had some changes that caused it to not work if used with an older version of #firebase/app.
So basically, it should work if you have either (1) no #firebase/app or (2) a current #firebase/app. Your error sounds most likely to be an existing outdated #firebase/app.
I know you said you don't seem to have #firebase/app in your project but since it seems like the most likely cause, I'm wondering if you have it in a parent directory. (It's installed as part of the Firebase Web SDK, as in npm install firebase.) Most firebase functions (if you use firebase init) are set up in a /functions subdirectory of the main project repo, with its own package.json, and the rest of the project is one level up and has another package.json. And that looks like it might be your dir structure?
In that case, running npm ls inside /functions will turn up an empty result, but if you go up to the parent dir (that contains the other package.json), it will show up. Node will go up a level if it doesn't find a package at the current one. See if you can ensure both levels are clean from any #firebase/app, delete both node_modules dirs, reinstall. If you do need it in the top level (for Firebase Web SDK), make sure it is upgraded the most current firebase (7.6.1).
As a last resort, maybe check to see if firebase is npm installed globally somehow.
If you definitely don't have #firebase/app at any level of your project and it's still failing, this is a bug we should look into.
Sorry that's a lot of info! Hope that wasn't too much. TLDR: I think you do probably have #firebase/app in your project root dir? If not, please file an issue on Github.
Based on #Christina Holland answer I investigated a bit further. When I ran npm ls #firebase/app in my Angular folder (functions is a subfolder of that) I got:
└─┬ UNMET PEER DEPENDENCY firebase#7.6.1
└── #firebase/app#0.5.0
npm ERR! peer dep missing: firebase#>= 5.5.7 <7, required by #angular/fire#5.2.1
I then updated #angular/fire to the newest version. It didn't change the #firebase/app version, but it removed the error:
└─┬ firebase#7.6.1
└── #firebase/app#0.5.0
After that I could remove #firebase/app from my a functions package.json and I could deploy without any errors.
I don't understand what happens here, but the problem is solved and maybe it can help some other developer with this problem.

Why does not the global npm package kick in for module dependency?

I have already installed my typescript and ts-node globally.
I have a package.json file like the following, and when I run npm test, everything works (NOTE: as you can see, ts-node and typescript are installed as local modules in this situation)
{
"name": "two_sum",
"version": "1.0.0",
"description": "two sum problem solver",
"main": "main.js",
"scripts": {
"test": "./node_modules/.bin/mocha --compilers ts:ts-node/register ./test/*.spec.ts"
},
"devDependencies": {
"chai": "^4.1.2",
"mocha": "^4.1.0",
"ts-node": "^4.1.0",
"typescript": "^2.6.2"
}
}
However, if I take two two modules out of the package.json (and delete the two packages from my ./mode_modules), i.e, ts-node and typescript are not installed locally, I got errors like this:
Error: Cannot find module 'typescript'
at Function.Module._resolveFilename (module.js:470:15)
....
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3
npm ERR! Test failed. See above for more details.
Here is my question: why would I need to have those two package installed locally? Why can't the global package kick in to resolve the dependency?
Globally installed packages are not involved in the resolution when your code runs.
This is because the project (denoted by the presence of your package.json) have no knowledge of what has been installed globally.
Globally installed packages ties to the environment, not the project.
If the globally installed packages are used in the resolution, then the project may work in your environment but not others.
So that will make the executability of your project not reliable (or put in another word, coupled or depended on your environment).
Nowadays, install global packages for CLI tools only.

Mocha TS tests fail with `npm test` but not if run directly

In my nodejs project (written in Typescript) I can run my tests with this command:
mocha --compilers ts:ts-node/register,tsx:ts-node/register
and they succeed. I also used this command in my package.json file so that
npm test
runs them the same way, however in this case I get:
Mikes-iMac:antlr4-graps mike$ npm test
> mocha --compilers ts:ts-node/register,tsx:ts-node/register
module.js:472
throw err;
^
Error: Cannot find module 'ts-node/register'
at Function.Module._resolveFilename (module.js:470:15)
My package.json file contains:
"scripts": {
"test": "mocha --compilers ts:ts-node/register,tsx:ts-node/register"
},
"devDependencies": {
"#types/chai": "^3.4.34",
"#types/mocha": "^2.2.32",
"#types/node": "^6.0.40",
"chai": "^3.5.0",
"mocha": "^2.5.3",
"typescript": "^2.0.3",
"vscode": "^1.0.0"
},
What is the correct variant to run mocha via npm?
The problem is that no matter what, but npm run <script> in general and npm test in particular will run command using /bin/sh, not your current shell, which is likely different.
Since you don't have ts-node in your dependencies, I assume it's installed globally. Depending on how you install Node.js, /bin/sh may end up using different Node.js installation than your current shell and therefore not have same globally installed package.
If I'm right these two commands will give different results:
$ which node
$ /bin/sh -c 'which node'
Two possible solutions:
Add ts-node to devDependencies of you project and npm install.
Ensure, that /bin/sh uses same installation of Node.js, as you current shell.

Connecting electron with sqlite3

I want to connect electron with sqlite3. My package.json file is listed below
{
"name": "electrontest2",
"version": "1.0.0",
"description": "",
"main": "db.js",
"scripts": {
"start": "electron ."
},
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC",
"devDependencies": {
"electron-prebuilt": "^1.2.2"
},
"dependencies": {
"jquery": "^2.1.4",
"sqlite3": "^3.1.4"
}
}
But while doing npm start it is throwing this error
App threw an error during load
Error: Cannot find module '/var/www/tools/node/project/electrontest2/node_modules/sqlite3/lib/binding/electron-v1.2-linux-x64/node_sqlite3.node'
at Module._resolveFilename (module.js:438:15)
at Function.Module._resolveFilename (/var/www/tools/node/project/electrontest2/node_modules/electron-prebuilt/dist/resources/electron.asar/common/reset-search-paths.js:47:12)
at Function.Module._load (module.js:386:25)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/www/tools/node/project/electrontest2/node_modules/sqlite3/lib/sqlite3.js:4:15)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
A JavaScript error occurred in the main process
Uncaught Exception:
Error: Cannot find module '/var/www/tools/node/project/electrontest2/node_modules/sqlite3/lib/binding/electron-v1.2-linux-x64/node_sqlite3.node'
at Module._resolveFilename (module.js:438:15)
at Function.Module._resolveFilename (/var/www/tools/node/project/electrontest2/node_modules/electron-prebuilt/dist/resources/electron.asar/common/reset-search-paths.js:47:12)
at Function.Module._load (module.js:386:25)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/www/tools/node/project/electrontest2/node_modules/sqlite3/lib/sqlite3.js:4:15)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
I think I am getting this error as i am having :
'/var/www/tools/node/project/electrontest2/node_modules/sqlite3/lib/binding/node-v46-linux-x64/node_sqlite3.node'
instead of
'/var/www/tools/node/project/electrontest2/node_modules/sqlite3/lib/binding/electron-v1.2-linux-x64/node_sqlite3.node'
Please tell where I am making mistake. Currently while running the app it is throwing the error listed above.
You're correct that the error is because the compiled SQLite module is named for Node by default; and thus Electron can't find it. Using node-gyp to rebuild with the correct name, as in the answer above should work; but it's a lot easier to use the npm package electron-builder which will give you a better workflow and work with multiple platforms and versions without having to add scripts for node-gyp.
See this answer to a similar question which details how to get it working.
Try rebuilding the sqlite3 package as follows:
cd node_modules/sqlite3
npm run prepublish
node-gyp configure --module_name=node_sqlite3 --module_path=../lib/binding/electron-v1.2-linux-x64
node-gyp rebuild --target=0.37.2 --arch=x64 --target_platform=linux --dist-url=https://atom.io/download/atom-shell --module_name=node_sqlite3 --module_path=../lib/binding/electron-v1.2-linux-x64
Check what is you electron version
electron -v
Replace --target value with the vesion of your electron package.
I tried running this with the latest Node version (6.2.2), if you are using an older version eg. the 4.2 then you will get an older bundle instead of the v48 your electron will need:
npm install sqlite3 --build-from-source
And simply renamed the folder in node_modules/sqlite3/lib/binding from node-v48-linux-x64 to electron-v1.2-linux-x64.
It started complaining about requiring callbacks were they are supposed to be optional, but I just added them like this and it worked:
var stmt = db.prepare(
"INSERT INTO discount VALUES (?, ?, ?)",
[1,2,3],
() => true //Expected callback that is supposed to be optional
);
I just needed the Sqlite in my electron app for simple purposes and didn't have any other problems in my implementation.
First add new postinstall script in your package.json
"scripts": {
"postinstall": "install-app-deps"
}
Then install it using :
npm install --save-dev electron-builder
npm install --save sqlite3
npm run postinstall
You can also find the same at :
Electron application SQLITE package has not been found installed

Node error: SyntaxError: Unexpected token import

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.

Resources