ES2015 modules does not work in Node.js with Babel.js? - node.js

I want to use ES2015 modules in Node.js with babel.js compiler, but it won't work. Here is what I have:
package.json
{
"name": "test",
"version": "0.0.1",
"private": true,
"scripts": {
},
"devDependencies": {
"babel-core": "^6.9.0",
"babel-plugin-transform-runtime": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-node5": "^11.1.0",
}
}
.babelrc
{
"presets": ["es2015"],
"plugins": [
"transform-runtime"
]
}
server/index.js
require('babel-core').transform('code', {
presets: ['node5'],
});
import { test } from './file1';
console.log(test);
server/file1.js
export const test = 'its working!';
But console throws error SyntaxError: Unexpected token import
Does ES2015 modules not working in node5, or I am doing something wrong here? Appreciate your help.

Please install babel-register npm module and require this in index.js
server/index.js
require('babel-register');
import { test } from './file1';
console.log(test);
package.json
{
"name": "test",
"version": "0.0.1",
"private": true,
"scripts": {
},
"devDependencies": {
"babel": "^6.5.2",
"babel-preset-es2015": "^6.6.0",
"babel-register": "^6.8.0"
}
}
.babelrc
{presets:[es2015]}
for me it works
Thanks

Related

[eslint][node.js] Parsing error in Eslint- How to use import fetch while preserving commonjs?

I'm trying to override eslint rules to enable import usage in node.js. The code works perfectly but eslint throws an error:
C:\...MORE.PATH.HERE...\shared\index.js
5:32 error Parsing error: Unexpected token import
There are reasons why I do not want to switch to ES modules and node-fetch documentation has provided me with this legit method of importing (require not available for the newest fetch). At the same time, I have to extend airbnb in eslint. To start with I'm working on "warn" but still getting only errors and 0 warnings.
Most recent versions of involved files:
.eslintrc
{
"extends": "airbnb",
"plugins": ["import"],
"settings": {
"import/no-import-module-exports": {
"node": {
"extensions": [".js"]
}
}
},
"rules": {
"import/no-import-module-exports": [
"warn",
{
"exceptions": ["**/shared/index.js"]
}
]
}
}
..\shared\index.js - the file with import usage
class OAuth {
constructor() { some stuff }
async getBearer(id, secret) {
const fetch = (url, init) =>
import('node-fetch').then(({ default: fetch }) => fetch(url, init));
const formatAuthUrl = tenant => `https://login.microsoftonline.com/${tenant}/oauth2/token`;
//THE REST IS IRRELEVANT
package.json (without some irrelevant dependencies)
{
"name": "my-backend",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "func start",
"test": "echo \"No tests yet...\"",
"lint": ".\\node_modules\\.bin\\eslint .\\"
},
"dependencies": {
"node": "^16.17.0",
"node-fetch": "^3.2.10",
"npm": "^8.19.1"
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^5.36.2",
"#typescript-eslint/parser": "^5.36.2",
"eslint": "^8.2.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-react": "^7.28.0",
"eslint-plugin-react-hooks": "^4.3.0",
"prettier": "2.7.1"
}
}
So far I've focused mostly on eslint-plugin-import as it seems potentially helpful, however, I'm not sure if I'm looking at the right plugin. Before that, I went through eslint rules. I also tried finding a solution in eslint-config-airbnb and in their files to find a name of a rule that may be the answer to this issue.
I am asking you for help as maybe I'm not noticing something, using the wrong plugin, or using it incorrectly.

configuring jest to run tests in a different folder

I have been trying to configure Jest so it could run test cases written in another folder in the same hierarchy. But it throws the below error.
I am trying to run jest from the as_test folder while my test case files and actual code to be tested resides in asCore folder.
I think Jest is unable to find enzyme as it resides in node_modules of as_test,while the test case which uses it resides in asCore folder.
Could someone help me how solve this problem.
● Test suite failed to run
Cannot find module 'enzyme' from 'Button.test.js'
1 |
> 2 | import { shallow, mount } from 'enzyme';
| ^
3 | import Button from '../JSX/Button';
4 |
5 |
at Resolver.resolveModule (as_test/node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (asCore/components/button/__tests__/Button.test.js:2:1)
The jest config files and my development reside in the below structure.
Package.JSON
{
"private": true,
"version": "0.0.0",
"name": "example-enzyme",
"dependencies": {
"react": "16.5.2",
"react-dom": "16.5.2"
},
"devDependencies": {
"#babel/core": "^7.1.2",
"#babel/node": "^7.0.0",
"#babel/preset-env": "^7.1.0",
"#babel/preset-react": "^7.0.0",
"#babel/register": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "*",
"babel-loader": "^8.0.4",
"jest": "*",
"react-test-renderer": "*",
"enzyme": "*",
"enzyme-adapter-react-16": "*",
"enzyme-to-json": "*",
"jest-html-reporter": "*"
},
"scripts": {
"test": "jest --no-cache"
}
}
Jest.config.js
const { resolve } = require('path');
const root = resolve(__dirname, '..');
console.log(root);
module.exports = {
"verbose": true,
"rootDir": root,
"setupTestFrameworkScriptFile": "<rootDir>/as_test/config/jestSetup.js",
"collectCoverage": true,
"coverageDirectory":"<rootDir>/as_test/coverage",
"coverageReporters": [
"html", "text"
],
"moduleDirectories": ["node_modules", "bower_components", "<rootDir>/*"],
"testResultsProcessor": "<rootDir>/as_test/node_modules/jest-html-reporter",
"snapshotSerializers": ["<rootDir>/as_test/node_modules/enzyme-to-json/serializer"],
"moduleNameMapper": {
"core/extendables/reactHelper$": "<rootDir>/as_test/deps/js/reactHelper.js",
"core/components/button/JSX-generated/Button$": "<rootDir>/as_test/deps/jsx/Button"
}
};
babel.config.js
module.exports = {
presets: [['#babel/preset-env'],'#babel/preset-react'],
};
JestSetup.js
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });

How to use babel-preset-env with Jest

We are in the midst of updating our API, and Henry Zhu from Babel alerted me to this preset called babel-preset-env to replace need for babel-preset-es2015 and babel-preset-es2018.
Now, I am encountering difficulty understanding the simplest way to handle everything.
Our API uses node v8.x and async/await, native promises
I want spread operator
I want pipeline operator
I want import/export syntax
I want to support Jest
I like how babel-node transpiles the API into memory
This will be easier if I just show you the current position of our config:
.babelrc
{
"presets": [
"env",
{
"targets": {
"node": "current"
}
},
"jest"
]
}
package.json
{
"scripts": {
"test": "node --harmony-async-await node_modules/jest/bin/jest.js",
"start:local": "NODE_ENV=localhost npm run babel-node -- warpcore/server.js",
"start": "npm run babel-node -- warpcore/server.js",
"babel-node": "babel-node --presets=es2015,stage-2"
},
"dependencies": {
"babel-polyfill": "^6.23.0"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.25.0",
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2018": "^1.0.0",
"babel-preset-stage-2": "^6.24.1",
"jest": "^20.0.4"
},
"jest": {
"testURL": "http://localhost:8080",
"testEnvironment": "node"
}
}
I am uncertain how these things need to be organized to best achieve my bullet list above.
What changes should I make?
I think the babel-node script needs to change
I suspect I can remove some of these packages
I suspect the .babelrc file isn't optimal
If you want to use babel-preset-env as a replacement for babel-preset-es2015 (which is deprecated) with Jest, then you have to make sure that the "modules" property in your "env" configuration is set to "commonjs".
Here is an exemplary configuration:
.babelrc
{
"env": {
"test": {
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
],
"presets": [
"jest",
"react",
[
"env",
{
"debug": false,
"modules": "commonjs",
"targets": {
"node": "current"
},
"useBuiltIns": true
}
]
]
}
}
}
You can see in env.test, that the preset env (which is the "babel-preset-env" configuration) has "modules" set to "commonjs". That's important, otherwise you will get "SyntaxError: Unexpected token import".
For completeness, here is a simple test:
ExampleButton.test.jsx
import ExampleButton from './ExampleButton';
import React from 'react';
import renderer from 'react-test-renderer';
test('Example Test', () => {
const component = renderer.create(<ExampleButton />);
const json = component.toJSON();
expect(json.type).toBe('button');
});
ExampleButton.jsx
import React from 'react';
class ExampleButton extends React.Component {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.text}
</button>
)
}
}
export default ExampleButton;
For my Babel setup, I have used the following dependencies:
"babel-core": "6.26.0",
"babel-jest": "21.2.0",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-object-rest-spread": "6.26.0",
"babel-preset-env": "1.6.1",
"babel-preset-react": "6.24.1",
"jest": "21.2.1",
"react-test-renderer": "16.1.1",
I think I got it working. Here is the solution:
.babelrc
The one posted in the question has a syntax error because the env preset needs to be wrapped in brackets[] (from: http://babeljs.io/docs/plugins/preset-env/)
Correct:
{
"presets": [
["env",
{
"targets": {
"node": "current"
}
}],
"jest"
]
}
package.json
The one posted in the question has a few things that can be removed:
{
"scripts": {
"test": "jest --verbose",
"start:local": "cross-env NODE_ENV=localhost babel-node -- app.js",
"babel-node": "babel-node --presets=env"
},
"dependencies": {
"babel-cli": "^6.24.1",
"babel-preset-env": "^1.6.0"
},
"devDependencies": {
"babel-eslint": "^7.2.3",
"babel-jest": "^20.0.3",
"jest": "^20.0.4"
},
"jest": {
"testURL": "http://localhost:8080",
"testEnvironment": "node"
}
}
Much cleaner in my opinion. You can modulate the presets from the .babelrc file if you want to explicitly include or exclude any, or specify which browsers to support.
This is the solution I found:
{
"presets": ["#babel/env", "#babel/react"]
}

Trying to use an async function with npm http-hash

I am trying to use http-hash module in order to construct an API for my application. I am using AVA as my test runner for my previous test. When I run the "npm test" command, I get this error in my console:
import { send } from 'micro'
^^^^^^
SyntaxError: Unexpected token import
I am using a linter and it doesn't send me any error. Here is my package.json, where you can see that I am using some babel plugins in order to transpile generators:
{
"name": "pos_lisa-api",
"version": "0.1.0",
"description": "LISA POS REST API",
"scripts": {
"lint": "standard",
"test": "npm run lint && ava"
},
"author": "Mauricio Cano Giraldo",
"license": "MIT",
"devDependencies": {
"ava": "^0.18.1",
"babel-eslint": "^7.1.1",
"babel-register": "^6.23.0",
"standard": "^8.6.0",
"test-listen": "^1.0.1"
},
"dependencies": {
"babel-plugin-transform-async-to-generator": "^6.22.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-es2015": "^6.22.0",
"babel-runtime": "^6.22.0",
"http-hash": "^2.0.0",
"micro": "^7.0.6",
"request": "^2.79.0",
"request-promise": "^4.1.1",
"uuid-base62": "^0.1.0"
},
"standard": {
"parser": "babel-eslint"
},
"babel": {
"presets": [
"es2015"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
}
And here is my node file, where i get the error:
'use strict'
import { send } from 'micro'
import httpHash from 'http-hash'
const hash = httpHash()
hash.set('GET /:id', async function getCliente (req, res, params) {
send(res, 200, params)
})
export default async function main (req, res) {
let method = req.method
let url = req.url
let match = hash.get(`${method.toUpperCase()} ${url}`)
if (match.handler) {
try {
await match.handler(req, res, match.params)
} catch (e) {
send(res, 500, { error: e.message })
}
} else {
send(res, 404, { error: 'La ruta no fue encontrada' })
}
}
I am reading around the web and I don't find anything. Please, help me! I would appreciate it so much!
AVA only transpiles the test files you want to run, but not the modules you're importing in them. But you can tell AVA to also transpile the imported modules by requiring babel-register (https://github.com/avajs/ava#transpiling-imported-modules). And because you configured babel already you can also tell it to use your config. Add this to your package.json
"ava": {
"babel": "inherit",
"require": ["babel-register"]
}
If you'd like to use the babel config AVA uses, you can leave off the "babel": "inherit", or you can define an entirely different one if you wish. But usually it's best to just inherit your config.
Using a .babelrc instead may work.

Trying to use async/await in mocha

I want to use async/await in mocha in order to make my tests. I have read many post, but I didn't find the solution. I have already install all the babel modules in order to transpiling the code, but it doesn't work.
Here is my code inside the "test" folder:
import test from 'mocha'
import 'babel-polyfill'
import { expect } from 'chai'
import { assert } from 'chai'
import utils from '../lib/utils'
describe('long number', function () {
it("Sample", mochaAsync(async () => {
var x = utils.longNums(0);
expect(x).to.equal(5000);
}))
})
Here is my package.json where I am using all the babel dependencies and plugins that I have read I have to install, and my test script where I suggest to mocha to use the babel transpiling
{
"name": "pos_lisa-test",
"version": "1.0.0",
"description": "pos lisa test",
"main": "index.js",
"scripts": {
"test": "mocha --compilers js:babel-core/register ./src/**/*.test.js"
},
"standard": {
"parser": "babel-eslint"
},
"babel": {
"presets": [
"es2015",
"react"
]
},
"keywords": [
"test"
],
"author": "Mauricio",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.23.1",
"babel-eslint": "^7.1.1",
"babel-plugin-transform-async-to-generator": "^6.22.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"chai": "^3.5.0",
"mocha": "^3.2.0",
},
"plugins": [
"transform-async-to-generator"
],
"dependencies": {
"babel-polyfill": "^6.23.0"
}
}
And the error that I get is the following
it('should remove items that don\'t evaluate to true when passed to predicate function', async function () {
^^^^^
SyntaxError: missing ) after argument list
What I am doing wrong? In advance thanks a lot for your help
You have added "plugins": ["transform-async-to-generator"]" to the top level of your package.json, but it should be inside the "babel" section. Change it to:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"transform-async-to-generator"
]
},
According to the Tao of Javascript, "Code flows in the moment, so knowledge is but a hint, like the map of a stream."
As of April, 2017, having the 'transform-async-to-generator' will actually cause problems.
As a more general note, every async function returns a promise, or casts its return value and exception to a promise. It is usually cleaner to test the promise and not have your test call await:
it('should have no drops left', () =>
ocean.listDrops().should.eventually.have.length(0));

Resources