unexpected reserved word import in node.js - javascript

I'm trying to run node.js backend server. I've received error unexpected reserved word on import in Node.js file.
The lines in file core.module.js is:
'use strict';
import lodashMixins from './lodashMixins.js'
... other imports and configurations ...
I launch simple command: node core.module.js
It's not uncommon error, but usually it happens with other libraries. I haven't seen solution for Node.js. How should I fix this? I'm using Windows Server.
Edit: I've find out that it's ES6, but how could I launch it? It looks like backend for the application, but I have no idea what command should I use to launch it without errors.

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

The import keyword is part of the modules feature in ECMAScript 2015, along with export and a few other specifications.
It is currently not implemented natively in NodeJS, even on the lastest version (v0.12.7), nor is it supported in the ES2015 "friendlier" fork iojs.
You will need to use a transpiler to get that to work.
[edit] it's still unsupported in the latest version (v5.8) despite the existence of an --harmony_modules flag, which does nothing. Your best run is to use babel, as explained here and here

I ran into this issue as I manually install any of these tools outside of Visual Studio. But Visual Studio ships with multiple open source command line tools that are used in modern web development workflows. Here’s how you can tell Visual Studio to use the same version that you have manually installed
Go to Tools –> Options –> Projects and Solutions –> External Web Tools
Set the global PATH environment variable before the internal path, you can just use the arrows at the top-right to change the order.
or
First, find the Node.js installation you already have and use at the command line. By default, Node.js 0.12.7 installs to “C:\Program Files\nodejs”. Add this entry at the top to the path to the node.js directory to force Visual Studio to use that version instead

This may not be the official answer, but I stumbled here after searching around for the 'unexpected reserved word'. After poking around, I discovered my problem was that, in fact, I just needed to run an npm install after having updated my branch from origin / rebasing. Hope this helps someone else who is furiously reverting their code trying to figure out what they broke! :)

Related

Error when Requiring Twilio Voice SDK Javascript

I have included (via npm) the twilio/voice-sdk package (v.2.1.0) into a project. When I include the following code (as shown in many examples):
const Device = require('#twilio/voice-sdk').Device;
I get a console error stating:
"Cannot find module 'events' in '#twilio/audioplayer/es5'". I am trying to import this onto the client side, not server.
I get this whether I use require or import.
As an attempt around this, I have also include the node package #twilio/audioplayer, but to no avail. Kind of stuck as to what is going on here.
I am trying to use this on a Wix (or Velo more specifically) project. Hoping to create a dialer that can both answer and instigate phone calls on a site that already exists on that platform.
I have installed both of the above npm packages into my project, but get he above enumerated error.
Any ideas from the Internet?
Additional Information:
If I add the 'require' on the server side I do not get the same error. I was going to try this and then do an async call to the server to get my Device object. However, the Twilio Device SDK package utilizes the Window object, which of course does not exist on the server side.
The #twilio/audioplayer package uses the "events" module. This module is available in Node.js and when applications are bundled with something like Webpack is polyfilled.
I haven't used Velo, but I assume they are bundling differently in a way that doesn't add polyfills for this. I'd recommend installing the events npm module to your project too. That should provide the EventEmitter that the library is using for the browser environment and stop this error.
I had a similar problem, where I can import Device, but cannot construct it. The problem I had was that the bundler (in my case Vite) doesn't have a polyfill to run some functions inside the #twilio/voice-sdk.
The solution in my case was by installing polyfill on Vite.
Here is how:
First, install these packages:
npm i #esbuild-plugins/node-globals-polyfill #esbuild-plugins/node-modules-polyfill --save-dev
Then add the polyfill config to your vite.config.js. Here is link of the code: https://medium.com/#ftaioli/using-node-js-builtin-modules-with-vite-6194737c2cd2.
Because I use React, I still need to add plugins: [react()] inside the polyfill config. So it becomes something like:
export default defineConfig({
plugins: [react()],
// rest of the polyfill config
})
Now you can do:
import { Device } from "#twilio/voice-sdk";
new Device(token);

Issues running auth0 with (npm) in a Chrome extension (javascript) [duplicate]

I tried so but I have a 'require is not defined' error. I can't find information about that, can someone enlighten the noob in me please?
It's possible, but you have to be careful. Trying to require() a package means that node will try to locate its files in your file system. A chrome extension only has access to the files you declare in the manifest, not your filesystem.
To get around this, use a module bundler like Webpack, which will generate a single javascript file containing all code for all packages included through require(). You will have to generate a separate module for each component of your chrome extension (e.g. one for the background page, one for content scripts, one for the popup) and declare each generated module in your manifest.
To avoid trying to setup your build system to make using require() possible, I suggest starting with a boilerplate project. You can check out my extension to see how I do it.
An updated answer for 2022
Short answer: yes, you can require/import packages. Rather than going through the tedious work of setting up & configuring a bundler like Webpack on your own (especially if you have no experience with them), there are now build tools you can use to create the boilerplate "scaffolding" for a Chrome extension:
Extension CLI -- this one is well-documented and you can also reference the source code of some Chrome extensions that have used this tool (READ: learn how others have set up their code).
Chrome Extension CLI
Benefits of using them:
New projects are initiated with a default project file structure. Super helpful.
They support modern Javascript (ES6, ES2021), so modules work fine.
They already have bundlers integrated and pre-configured (Webpack in both above cases I think). You therefore don't need to install and configure any on your own.
You can use npm as normal to install any packages/dependencies you need.
Then of course, let the official documentation for Chrome Extensions guide you through the rest.
It's not possible to require node modules directly within a chrome extension. However, it is possible to bundle node applications and packages into the browser for use with your extensions. See here for more: Is it possible to develop Google Chrome extensions using node.js?
Yes, It is possible with esm npm packages.
require is commonjs module loader.
Browser doesn't support commonjs modules system
so that this error showed.
Method 1:
Run npm init -y and add "type" :"module" in your package.json.
create path.js file
add this line in path.js
const fullPath = await import.meta.resolve("npm-pkg-name");
const path = fullPath?.match(/(/node_modules.*)/)[0];
console.log(path);
add this line inside package.json
"path": "node --experimental-import-meta-resolve path.js",
Copy console output text. Replace package name with this copied path.
Method 2:
Install other npm package to find and replace
npm packages' virtual path to real path so that chrome browser will find it.
Install Path-fixxer
Add this line in path.js
import setAllPkgPath from "path-fixxer";
setAllPkgPath();
then run command : npm run path.
Now open browser to test it.

Importing npm modules into Google Chrome Extension content script [duplicate]

I tried so but I have a 'require is not defined' error. I can't find information about that, can someone enlighten the noob in me please?
It's possible, but you have to be careful. Trying to require() a package means that node will try to locate its files in your file system. A chrome extension only has access to the files you declare in the manifest, not your filesystem.
To get around this, use a module bundler like Webpack, which will generate a single javascript file containing all code for all packages included through require(). You will have to generate a separate module for each component of your chrome extension (e.g. one for the background page, one for content scripts, one for the popup) and declare each generated module in your manifest.
To avoid trying to setup your build system to make using require() possible, I suggest starting with a boilerplate project. You can check out my extension to see how I do it.
An updated answer for 2022
Short answer: yes, you can require/import packages. Rather than going through the tedious work of setting up & configuring a bundler like Webpack on your own (especially if you have no experience with them), there are now build tools you can use to create the boilerplate "scaffolding" for a Chrome extension:
Extension CLI -- this one is well-documented and you can also reference the source code of some Chrome extensions that have used this tool (READ: learn how others have set up their code).
Chrome Extension CLI
Benefits of using them:
New projects are initiated with a default project file structure. Super helpful.
They support modern Javascript (ES6, ES2021), so modules work fine.
They already have bundlers integrated and pre-configured (Webpack in both above cases I think). You therefore don't need to install and configure any on your own.
You can use npm as normal to install any packages/dependencies you need.
Then of course, let the official documentation for Chrome Extensions guide you through the rest.
It's not possible to require node modules directly within a chrome extension. However, it is possible to bundle node applications and packages into the browser for use with your extensions. See here for more: Is it possible to develop Google Chrome extensions using node.js?
Yes, It is possible with esm npm packages.
require is commonjs module loader.
Browser doesn't support commonjs modules system
so that this error showed.
Method 1:
Run npm init -y and add "type" :"module" in your package.json.
create path.js file
add this line in path.js
const fullPath = await import.meta.resolve("npm-pkg-name");
const path = fullPath?.match(/(/node_modules.*)/)[0];
console.log(path);
add this line inside package.json
"path": "node --experimental-import-meta-resolve path.js",
Copy console output text. Replace package name with this copied path.
Method 2:
Install other npm package to find and replace
npm packages' virtual path to real path so that chrome browser will find it.
Install Path-fixxer
Add this line in path.js
import setAllPkgPath from "path-fixxer";
setAllPkgPath();
then run command : npm run path.
Now open browser to test it.

Modules and dynamic importing in Mozilla addon

I found a convenient way of turning my Chrome extension into modules (a lot easier to maintain etc.). I made it like this https://stackoverflow.com/a/53033388/9182284 (turning background.js into a module and then using dynamic import to get modules).
The simplified version of importing:
(async () => {
const src = chrome.extension.getURL("your/content_main.js");
const contentMain = await import(src);
contentMain.main();
})();
My question is: how could I implement it in Mozilla Firefox? As I am developing for both browsers (first for Chrome and then later copy stuff over to Firefox files and change what's needed). Earlier I just went the easy way and included all the functions in the files they are needed for Firefox version but as I have like 20 files at least then it gets dull do edit all of them etc.
When I try to use dynamic import in Firefox addon then it just doesn't load the script at all (no error log or anything in console) so I don't exactly know the problem (does Firefox just not support it at all?).
If you don't mind using a build tool, I found that parcel works pretty well for this. Use the web extension plugin.
Install via NPM
$ npm install parcel parcel-plugin-web-extension --save-dev
Build from the terminal
$ parcel build --out-dir dist-firefox dist/manifest.json

babel-cli vs babel-preset-es2015 vs babel-register vs babel-core?

What are all these babel dependencies? What are each of them for and how do they differ? Which one should I use for my nodejs web app?
I have looked on the API website but is there any guide that puts these into simple human English?
In simple terms:
babel-cli: Is the one you would use if you were trying to
compile an ES6/ES7 module to ES5- and you had a need to do that via a
terminal command.
babel-preset-es2015: Is the package containing
a subset of features that ES6/ES7 provides.
babel-register: A
require that you do and causes every file require there after to run
through babel, thus allowing you to write ES6/ES7 code in every module.
babel-core: Same as "babel-cli" except you would use it programmatically inside your app.
Basically, you could use "babel-register" during development with the "babel-preset-es2015" package set. Then use "babel-cli" or "babel-core" to compile your files before production.
I hope that helps.

Categories

Resources