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.
Related
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.
When I deploy the nodejs application in vercel it shows this error in function logs,
I have already deployed the nodejs application with the same config and file directory this is the first time I am seeing this serverless function error
I want to deploy the nodejs server to vercel because soon Heroku will remove its free tier so please find the issue or if you guys have any recommendations to deploy the nodejs server please let me know
[GET] /
15:11:45:53
Function Status:
None
Edge Status:
500
Duration:
94.00 ms
Init Duration:
N/A
Memory Used:
19 MB
ID:
sfo1::7wz8g-1667209305700-0df0949052b6
User Agent:
got (https://github.com/sindresorhus/got)
2022-10-31T09:41:45.636Z 0a0d2c9e-7a8b-46f1-89b7-bf1ea6108d53 ERROR Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/var/task/Controllers/Users.controller.js' imported from /var/task/routes/Users.routes.js
at new NodeError (node:internal/errors:372:5)
at finalizeResolution (node:internal/modules/esm/resolve:437:11)
at moduleResolve (node:internal/modules/esm/resolve:1009:10)
at defaultResolve (node:internal/modules/esm/resolve:1218:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:580:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:294:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
at link (node:internal/modules/esm/module_job:78:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
RequestId: 0a0d2c9e-7a8b-46f1-89b7-bf1ea6108d53 Error: Runtime exited with error: exit status 1
Runtime.ExitError
// Users.routes.js
import express from "express";
import { get_id, addUser, addFriends, getFriends, getPendingFriends, queryUser, startChat, getChats, getUser, getUserServers, changeUserName, createServers, joinServers } from "../Controllers/Users.controller.js";
const router = express.Router();
// get user id
router.get("/getId", async (req, res, next) => {
try {
const { uid } = req.query;
const id = await get_id(uid);
res.status(200).send(id);
} catch (error) {
console.log(error)
next(error);
}
});
// add user to the database
router.post("/addUser", addUser);
// search a user through username using get method and query
router.get("/searchUser", queryUser);
// start the chat
router.post("/startChat", startChat);
// get all chats
router.get("/getChats", getChats);
// get logged in user
router.get("/getUserInfo", getUser);
// send and accept the friend request
router.post("/add-friends", addFriends);
// get Accepted Friends
router.get("/getAllFriends", getFriends);
// get Pending Friends
router.get("/getPendingFriends", getPendingFriends)
// create a new server for the user
router.post("/createServer", createServers);
// join a new server for the user
router.post("/joinServer", joinServers);
// getting all servers that users have already joined
router.get("/getallServers", getUserServers);
// change username
router.post("/changeUserName", changeUserName);
export default router;
// package.json
{
"name": "user-and-chat-service",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"license": "MIT",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon index.js",
"watch": "babel-watch -L src/index.js"
},
"devDependencies": {
"babel-watch": "^7.7.0"
},
"dependencies": {
"#babel/core": "^7.19.1",
"#babel/polyfill": "^7.12.1",
"#babel/preset-env": "^7.19.1",
"#vercel/node": "^2.5.22",
"axios": "^0.27.2",
"babel-plugin-module-resolver": "^4.1.0",
"cors": "^2.8.5",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"http-errors": "^2.0.0",
"joi": "^17.6.1",
"mongoose": "^6.6.2",
"morgan": "^1.10.0",
"nanoid": "^4.0.0",
"nodemon": "^2.0.20"
}
}
// vercel.json
{
"builds": [
{
"src": "./index.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/index.js"
}
]
}
replace this for this, vercel.json not working with absolute paths
{
"builds": [
{
"src": "index.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "index.js"
}
]
}
I too had the same issue and I followed the official documentation. I worked well.
Using Express.js with Vercel
You should create an api directory and move the main server file to it.
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"]
}
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));
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