Node js import syntaxerror unexpected reserved word

import is a part of ECMAScript 2015 (ES6) standard and as Amit above mentioned it is not currently implemented natively in Nodejs.

So you can use transpiler like babel to run your es6 script

npm install babel

An example based on this answer

app.js

 import {helloworld,printName} from './es6'
 helloworld();
 printName("John");

es6.js

 module.exports = {
    helloworld: function() { console.log('hello world!'); },
    printName: function(name) { console.log(name); }
}

And using require hook in start.js

require("babel/register");
var app = require("./app.js");

And start your app as

node start.js

EDIT
The above answer was base on babel v5.8.23. For babel >= v6

Use require hook in start.js as

require('babel-core/register');
require("./app.js");

Also, transformations are not enabled by default. So you will need to install a preset. In this case use es2015

npm install babel-preset-es2015

And use it in a .babelrc file in root folder

{
   "presets": ["es2015"]
}

Using Babel in my NodeJSv4.1.1 code.

Got the require hook in:

require("babel-core/register");

$appRoot = __dirname;

module.exports = require("./lib/controllers/app");

In a subsequently lodaded .js file I am doing:

import { Strategy as LocalStrategy } from "passport-local";

However this is generating the following error in the CLI:

import { Strategy as LocalStrategy } from "passport-local";
^^^^^^

SyntaxError: Unexpected reserved word
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at loader (/Users/*/Documents/Web/*/node_modules/babel-core/node_modules/babel-register/lib/node.js:128:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/*/Documents/Web/*/node_modules/babel-core/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at module.exports (index.js:9:5)
    at Object.<anonymous> (app.js:102:39)

Felix Kling's user avatar

Felix Kling

787k173 gold badges1084 silver badges1134 bronze badges

asked Nov 14, 2015 at 15:59

rcjsdev's user avatar

10

Sounds like you aren’t using the right presets. As of babel 6, the core babel loader no longer includes the expected ES6 transforms by default (it’s now a generic code transformer platform), instead you must use a preset:

require('babel-register')({
        "presets": ["es2015"]
});

You will also need to install the preset package:

npm install --save-dev babel-preset-es2015

answered Jan 7, 2016 at 16:57

Arkadiy Kukarkin's user avatar

10

It seems that this file is not being transpiled. Is this subsequently loaded .js file in the node_modules directory? If so, you need to:

require("babel-core/register")({
  // This will override `node_modules` ignoring - you can alternatively pass
  // an array of strings to be explicitly matched or a regex / glob
  ignore: false
});

By default all requires to node_modules will be ignored. You can override this by passing an ignore regex

https://babeljs.io/docs/usage/require/

answered Nov 14, 2015 at 16:42

pherris's user avatar

pherrispherris

16.9k8 gold badges42 silver badges58 bronze badges

1

I was hitting the problem when trying to run tests via mocha, and I solved it by putting this in my package.json file:

"babel": {
    "presets": [
      "es2015"
    ]
},

I’m not completely clear on how this works. I’m running tests like this:

mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive

Eventually, this will all make sense I suppose.

answered Apr 22, 2017 at 16:51

Cameron O'Rourke's user avatar

  • Version: v13.9.0
  • Platform: Linux PC_NAME 5.3.0-40-generic docs: replace all instances of node.js with io.js because trademark. #32~18.04.1-Ubuntu SMP Mon Feb 3 14:05:59 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
  • Subsystem:

What steps will reproduce the bug?

Consider the following code:

a.mjs

(async () => {
    "use strict";
    
	let b = await import("./b.mjs");
	await b.default();
})();

b.mjs

import fs from 'fs';

function bug() {
	// The something doesn't have to exist
	console.log(await fs.promises.readFile("/proc/cpuinfo", "utf-8"));
}
export default async function () {
	await bug();
}

Explanation

There is obviously a bug in b.mjs above. The bug() function is missing the async keyword`. However, when I attempt to execute the above, I get the following error:

(node:30870) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected reserved word
    at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)
    at async link (internal/modules/esm/module_job.js:37:21)
(node:30870) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:30870) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This isn’t particularly helpful. Now, consider the following snippet:

c.mjs:

import fs from 'fs';

function bug() {
	// The something doesn't have to exist
	console.log(await fs.promises.readFile("/proc/cpuinfo", "utf-8"));
}

(async () => {
    "use strict";
    
    await bug();
})();

There’s bug in this one too, but executing it yields a very different and much more helpful error:

file:///tmp/c.mjs:5
	console.log(await fs.promises.readFile("/proc/cpuinfo", "utf-8"));
	            ^^^^^

SyntaxError: Unexpected reserved word
    at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)
    at async link (internal/modules/esm/module_job.js:37:21)

Much better. Node gives us a helping hand by telling us where the error occurred.

How often does it reproduce? Is there a required condition?

This bug in the error message only appears to occur when a module is dynamically imported with import("./path/to/file.mjs"). Specifically, the first error message is missing this bit:

file:///tmp/c.mjs:5
	console.log(await fs.promises.readFile("/proc/cpuinfo", "utf-8"));
	            ^^^^^

…obviously the filepath and line number would be different for b.mjs is this bit was added.

What is the expected behavior?

The first error message should look like the second.

When dynamically importing a module that is missing the async keyword on a method, the error message should tell me where the error occurred.

What do you see instead?

The bit there it tells me where the «unexpected reserved word» was found is missing. See above for examples of what’s gone wrong.

Additional information

If possible, when it’s the await keyword that was detected as unexpected, the error message should reflect this more closely. For example, it might be helpful to say `SyntaxError: Unexpected reserved word «await» (did you forget the «async» keyword?)» or something like that.

The “unexpected reserved word (await)” error occurs in JavaScript when you use the await keyword in a function that is not specified as async. To fix it, add an async modifier to the function to mark it as async.

The "Unexpected reserved word 'await'" error occurring in JavaScript.

The “Unexpected reserved word ‘await’” error occurring in JavaScript.

Here’s an example of the error occurring:

function getName() { // ❌ SyntaxError: Unexpected reserved word const str = await Promise.resolve('Coding Beauty'); return str; }

Note: As this is a syntax error, the function doesn’t need to be invoked for it to be detected, and no part of the code runs until it is resolved.

The async and await keywords work together in JavaScript (hence the commonly used term, async/await); to use the await keyword in a function, you must add the async modifier to the function to specify that it is an async function.

// ✅ Use "async" keyword modifier async function getName() { // ✅ Successful assignment - no error const str = await Promise.resolve('Coding Beauty'); return str; }

Fix “Unexpected reserved word (await)” error in nested function

If you’re using the await keyword, it’s likely that you already know that it has to be in an async function. What probably happened is that you nested functions and mistakenly ommited the async modifier from the innermost function containing the await keyword.

For example:

// ❌ SyntaxError: Unexpected reserved word export const createTask = async ({ description }) => // ❌ "async" keyword missing from innermost function (dispatch) => { await fetch('https://example.com/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ description }), }); dispatch({ type: 'taskCreated', description }); };

For await to work, the deepest function in the nesting hierarchy is required to be specified as async. It won’t work even if any or all of the outer functions are marked as async.

So we resolve the error in this case by adding the async modifier to the innermost function:

// ✅ No error export const createTask = async ({ description }) => // ✅ Innermost function marked as async async (dispatch) => { await fetch('https://example.com/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ description }), }); dispatch({ type: 'taskCreated', description }); };

In this example, we should be able to remove the async keyword from the outer function, as it isn’t performing any asynchronous operations with await, but this depends on whether the caller of createTask() is expecting it to return a Promise or not.

Here’s another example where this mistake frequently happens; using await in an array looping method:

// ❌ SyntaxError: Unexpected reserved word async function processPhotos(photoIds) { const data = await Promise.all(photoIds.map((photoId) => { const res = await fetch(`http://example.com/photos/${photoId}`); return await res.json(); })); // process data... }

Like in the previous example, the error occurs because the async keyword modifier is absent from the map() callback, even though it’s present in the function that calls map(). The fix is the same, add async to the map() callback.

// ✅ No error async function processPhotos(photoIds) { const data = await Promise.all( photoIds.map(async (photoId) => { const res = await fetch(`http://example.com/photos/${photoId}`); return await res.json(); }) ); // processing... }

Use await at top level

If you’re trying to use await at the top level of your file, you’ll need to set the type attribute to "module" in the script tag referencing the file in the HTML. This works when your code runs in browser environments.

For example:

<script type="module" src="index.js"></script>

Now you’ll be able to use await at the global scope in your file, e.g.:

console.log(await Promise.resolve('Coding Beauty'));

If you’re using Node.js, you’ll need to set the type attribute to "module" in your package.json file.

{ "name": "cb-js", "type": "module", "version": "1.0.0", "main": "index.js", "license": "MIT", // other fields... }

If there’s no package.json in your project directory, you can create one with the following command

# NPM npm init -y # Yarn yarn init -y

The await keyword will now work at the top level of your project files.

Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

Hi!

I’m having a lot of trouble trying to compile with npm on Ubuntu 22.04

What can I do to fix it? I’m using node 12 and can’t find anyway to install 14 or 16

npm run dev

> dev
> vite

file:///media/kaio/hdd/project_folder/node_modules/vite/bin/vite.js:7
    await import('source-map-support').then((r) => r.default.install())
    ^^^^^

SyntaxError: Unexpected reserved word
    at Loader.moduleStrategy (internal/modules/esm/translators.js:133:18)
    at async link (internal/modules/esm/module_job.js:42:21)

==================================EDIT==================================

Maybe not the best way, but it works for me:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
nvm install node
apt auto-remove nodejs
nvm install v16
nvm use v16

And then restart all terminals.

For some reason, it only works without nodejs .-.

# Curl command got from: https://github.com/nvm-sh/nvm#installing-and-updating

Using Babel in my NodeJSv4.1.1 code.

Got the require hook in:

require("babel-core/register");  $appRoot = __dirname;  module.exports = require("./lib/controllers/app"); 

In a subsequently lodaded .js file I am doing:

import { Strategy as LocalStrategy } from "passport-local"; 

However this is generating the following error in the CLI:

import { Strategy as LocalStrategy } from "passport-local"; ^^^^^^  SyntaxError: Unexpected reserved word     at exports.runInThisContext (vm.js:53:16)     at Module._compile (module.js:413:25)     at loader (/Users/*/Documents/Web/*/node_modules/babel-core/node_modules/babel-register/lib/node.js:128:5)     at Object.require.extensions.(anonymous function) [as .js] (/Users/*/Documents/Web/*/node_modules/babel-core/node_modules/babel-register/lib/node.js:138:7)     at Module.load (module.js:355:32)     at Function.Module._load (module.js:310:12)     at Module.require (module.js:365:17)     at require (module.js:384:17)     at module.exports (index.js:9:5)     at Object.<anonymous> (app.js:102:39) 

Sounds like you aren’t using the right presets. As of babel 6, the core babel loader no longer includes the expected ES6 transforms by default (it’s now a generic code transformer platform), instead you must use a preset:

require('babel-register')({         "presets": ["es2015"] }); 

You will also need to install the preset package:

npm install --save-dev babel-preset-es2015 

It seems that this file is not being transpiled. Is this subsequently loaded .js file in the node_modules directory? If so, you need to:

require("babel-core/register")({   // This will override `node_modules` ignoring - you can alternatively pass   // an array of strings to be explicitly matched or a regex / glob   ignore: false }); 

By default all requires to node_modules will be ignored. You can override this by passing an ignore regex

https://babeljs.io/docs/usage/require/

Понравилась статья? Поделить с друзьями:
  • Node js excel parser
  • No word for fun in russian
  • Node js excel import
  • Node js excel export
  • Node js create excel