getting a import statement error in node js - javascript

I started learning node.js recently.
I was using vs code and going through url module and got this error.
PS G:\node js> node "g:\node js\urlmodule.js"
(node:1964) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
g:\node js\urlmodule.js:1
import url from 'url';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
the code was-
import url from 'url';
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
console.log(myURL)
console.log(myURL.href)

Try to set:
"type": "module"
In your package.json file.

You have to include "type": "module" in package.json file.

Looks like you don't have setup to support es6 imports. Try using commonJS imports:
Eg: const url = require('url');
If you wanna use es6 import please follow this.

Related

Why am I getting the 'SyntaxError: Cannot use import statement outside a module' error while using the cloudinary module?

I am trying to call the cloudinary module to resize an image. This is my code:
import cloudinary from 'cloudinary';
var cl = new cloudinary.Cloudinary({ cloud_name: "username", secure: true });
new CloudinaryImage("pingu.jpg").resize(scale().width(70).height(53));
Here's the error I'm getting:
(node:29424) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
c:\Users\...\perspective\cloud.js:1
import cloudinary from 'cloudinary';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1018:16)
at Module._compile (node:internal/modules/cjs/loader:1066:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
[Done] exited with code=1 in 0.183 seconds
Can anyone tell me why I'm getting this specific error?
Use commonJs:
const cloudinary = require('cloudinary');
'Import' can only be used when the Node.JS file is ran as a module. Go to your package.json, and add in a key 'type' and the value 'module'.
{
"name": "test",
"version": "1.0.0",
"dependencies": {
...
}
}
to
{
"name": "test",
"version": "1.0.0",
"dependencies": {
...
},
"type": "module"
}
Alternatively, you could change your code from and then you don't need to edit your 'package.json' file
import something from Something
to
const something = require('Something')

Why nodejs didnt require p-queue?

I want to use p-queue npm nodejs. But it get me error. Help me why it was and how to fix it? Here my code:
const shell = require("shelljs");
const async = require("async");
const fs = require("fs");
const path = require("path");
const { default: PQueue } = require("p-queue");
const queue = new PQueue({ concurrency: 1 });
And this error:
internal/modules/cjs/loader.js:1080
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:
C:\Users\Feruz\Desktop\codeMaster\judge\node_modules\p-queue\dist\index.js
require() of ES modules is not supported. require() of
C:\Users\Feruz\Desktop\codeMaster\judge\node_modules\p-queue\dist\index.js
from C:\Users\Feruz\Desktop\codeMaster\judge\judge.js is an ES module
file as it is a .js file whose nearest parent package.json contains
"type": "module" which defines all .js files in that package scope as
ES modules. Instead rename index.js to end in .cjs, change the
requiring code to use import(), or remove "type": "module" from
C:\Users\Feruz\Desktop\codeMaster\judge\node_modules\p-queue\package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Users\Feruz\Desktop\codeMaster\judge\judge.js:5:29)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14) { code: 'ERR_REQUIRE_ESM' } [nodemon] app crashed - waiting for file
changes before starting...

Syntax error: Unexpected token { on executing a TS app

I have the following code in TypeScript:
import { Document, Schema, Model, model } from "mongoose";
import { IUser } from "../interfaces/IUser";
export interface IUserModel extends IUser, Document {
}
var UserSchema: Schema = new Schema({
name: String,
username: String,
password: String,
email: String
});
export const User: Model<IUserModel> = model<IUserModel>("User", UserSchema);
Then I use it in a controller. When I compile my TS app (tsc app.ts) it compiles fine. Then when I type "node app.js" in the terminal I get this error:
..\BlocG\models\user.ts:1
(function (exports, require, module, __filename, __dirname) { import { Document, Schema, Model, model } from "mongoose";
^
SyntaxError: Unexpected token {
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:656:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (E:\Business\Cevian\CevianPrep\BlocG\data\db.ts:26:1)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
What makes it even stranger is that I have such imports in the controller:
import { Router, Request, Response } from 'express';
import { IUserModel } from '../models';
...and it compiles with no problem. I used to execute the logic without any problems.
Please note that the error is not pointed at the import keyword but rather the curly bracket.
Please help me with this issue! Thanks in advance!
Then when I type "node app.js" in the terminal I get this error:
Change your tsconfig module option to be something that will work both in node (natively) and browser (using e.g. webpack):
"module": "commonjs"
As it turns out, the basic problem was that I was compiling like this:
tsc app
Instead of just writing
tsc
This caused my compilation types to mix with the js ones in the same folder.
Also, I had imports directly from [name].ts files, where I should've used file names only.

Angular 2 "require is not defined"

I am working on an app, which previously worked. I am now trying to add some routing, so have created an app.component file and changed a few parameters, but now I just get a blank screen and this error in the console...
Error: ReferenceError: require is not defined
at eval (http://localhost:3000/client/dev/main.js:2:17)
at eval (http://localhost:3000/client/dev/main.js:6:3)
at $ (http://localhost:3000/node_modules/systemjs/dist/system-polyfills.js:4:8740)
Evaluating http://localhost:3000/client/dev/main.js
Error loading http://localhost:3000/client/dev/main.js
My Main.JS file is:
"use strict";
var browser_1 = require('angular2/platform/browser');
var app_component_1 = require('./app.component');
browser_1.bootstrap(app_component_1.AppComponent);
This is Generated from main.ts:
import { bootstrap } from 'angular2/platform/browser';
import { AppComponent } from './app.component';
bootstrap(AppComponent);
Whats's wrong with this?
Update:
Thanks Eric for your suggestion about using the system module in tsconfig.json, but if I do it, I get the following error:
C:\Users\George\Source\Repos\Gen-App\server\server.js:2
System.register(['express', 'os', 'http', './config/routes.conf', './config/db.conf', './config/passport', './routes/index'], function(exports_1, context_1) {
^
ReferenceError: System is not defined
at Object.<anonymous> (C:\Users\George\Source\Repos\Gen-App\server\server.js:2:1)
at Module._compile (module.js:413:34)
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 Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object.<anonymous> (C:\Users\George\Source\Repos\Gen-App\index.js:1:63)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
NB: my server.js code is here
You say you added some routing and now it's not working. Your index.html file needs to include the router.dev.js file:
<script src="node_modules/angular2/bundles/router.dev.js"></script>

Node and Require import error in Mocha?

I have a working Node application and I'm trying to add Mocha tests, but getting some odd import errors.
This is my file structure:
package.json
index.js
src/
chart.js
highcharts-options.js
test/
test_chart.js
This is what my chart.js file looks like:
var chartOptions = require('./highcharts-options');
var analyseChart = {
doSomething: function() { ... }
};
module.exports = analyseChart;
And this is what highcharts-options.js looks like:
var HighCharts = require('highcharts-browserify');
Highcharts.theme = { ... };
Currently I import everything from /src into a single index.js file, then bundle it with browserify, which works just fine, no errors in the application.
Now I want to start writing Mocha tests for the functions in /src.
This is my first stub in test_chart.js:
var chart = require('../src/chart');
chart.doSomething();
But when I run mocha, I get the following error:
Users/.../js/src/highcharts-options.js:11
Highcharts.theme = {
^
ReferenceError: Highcharts is not defined
at Object.<anonymous> (/Users/.../js/src/highcharts-options.js:11:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/.../js/src/chart.js:7:20)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/.../js/test/test_chart.js:1:75)
How can I fix this import error for Mocha?
var HighCharts = require('highcharts-browserify');
Highcharts.theme = { ... };
You have a spelling error.
High[cC]harts
How did you not notice this yourself even when you were told exactly what was wrong?
Some errors are so common that we ultimately stop trusting them, and start looking for other faults in our code without even investigating it.
This is especially true for the "someVar is undefined" error in javascript.
Takeaway:
Sometimes you just got to trust your error messages.

Categories