Bring in a class using an NPM package that contains several classes

When attempting to import classes from my NPM package in main.js, I encountered an issue.

import { Organization, Club } from "sqorz-client";

o = new Organization();
o.setId("id");
c = new Club();
c.setId("anotherid");

The error message it returned was :

import { Organization } from "sqorz-client";
^^^^^^

SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1175:20)
at Module.\_compile (node:internal/modules/cjs/loader:1219:27)
at Module.\_extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module.\_load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint \[as runMain\] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47 \

My NPM package contains various classes which are exported using export class syntax...

This code within the classes is correct, as confirmed by successful unit tests with Jest. However, when attempting to import these classes into another project, it does not function as expected.

Sample code from my package :

index.js

import { Organization } from "./src/types/organization";
import { Club } from "./src/types/club";
import { SqorzClient } from "./src/SqorzClient";
import { Event } from "./src/types/event";
import { Pilot } from "./src/types/pilot";
import { Race } from "./src/types/race";
import { SqorzRequest } from "./src/services/sqorzRequest";

module.exports = { Organization, Club, SqorzClient, Event, Pilot, Race, SqorzRequest };

src/types/organization.js ( compiled by tsc )

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Organization = void 0;
class Organization {
    getId() {
        return this._id;
    }
    setId(id) {
        this._id = id;
        return this;
    }
    getName() {
        return this._name;
    }
    setName(name) {
        this._name = name;
        return this;
    }
    getCode() {
        return this._code;
    }
    setCode(code) {
        this._code = code;
        return this;
    }
}
exports.Organization = Organization;

package.json

{
  "name": "sqorz-client",
  [...]
  "files": [
    "src"
  ],
  "main": "index.js",
  [...]
}

I have tried various solutions like:

  • using module.exports = class in Organization.js,
  • changing the main file,
  • adjusting the source file list,
  • and more...

Answer №1

Make sure to configure your project as a module in order to use the import statement effectively.

Within your application, confirm that the following code is included in your package.json file:

{
    ... 
    "type": "module",
    ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Angular.copy() function selectively copies properties and does not duplicate everything

Exploring a function within a service: $scope.addPeriod = function(newPeriod) { if(newPeriod.from !== '' && newPeriod.until !== '') { var index = $scope.newPeriods.indexOf(newPeriod); ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Solving the TypeScript error: "Element implicitly has an 'any' type because an expression of type 'string' cannot be used to index type"

I'm having difficulty properly declaring a variable in my code. Here is the code snippet I am working with: ngOnInit(): void { this.activatedRoute.fragment.subscribe(numberOfTab => { if (numberOfTab) { this.tabs[numberOfTab].active = true; } else ...

Modify the attribute of numerous elements when hovering by implementing CSS transformations

I have a pair of adjacent div elements and I want to modify the background-color attribute of both when the user hovers over one of them. Initially, both divs should have a background-color set to #d8d8d8, and this color should change to #cacaca on both d ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

"The functionality of the RequireJS module shim is not functioning as expected during testing with Jasmine

In my JavaEE project, I am using RequireJS to load several third-party frameworks. One of these frameworks is OpenLayers3, which creates a global variable called "ol." Although OpenLayers3 is AMD compatible, a plugin I am using called "olLayerSwitcher" dep ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

Tips for successfully passing multiple props in a React functional component

Recently, I've delved into working with ReactJS using TypeScript and have been encountering stumbling blocks along the way. However, one particular issue has me stumped. Here is the task at hand: In the index page, I've set a tag <meta name= ...

Transferring a boolean model value to a JavaScript function triggers a reference to the onchange function

An onchange event is triggered in an input tag of type checkbox, calling a JavaScript function and passing three parameters from the model: <input type="checkbox" ... onchange="changeRow('@Model.Id', '@Model.Type', @Model.AwaitingAp ...

How to verify that the user is using the most up-to-date version of the application in React Native

Currently, I am focused on the application and have implemented API endpoints that return the latest version along with information on whether the update is mandatory. Within the application flow, a GET request is sent to these API endpoints to check the ...

using javascript to trigger android function

Looking to create a button in HTML that triggers a call from an Android device via JavaScript. Here is the code snippet I have tried, but it's not functioning as expected. Please note, I am new to Android development: public class MainActivity extend ...

Include buttons in the HTML template once JSON data has been received

I am working on a feature to dynamically add buttons to the DOM using JSON data fetched from an API when users visit the site. Although I have successfully implemented the function to retrieve the data, I am facing challenges in adding these buttons dynami ...

What are the security benefits of using Res.cookie compared to document.cookie?

When it comes to setting cookies to save data of signed in members, I faced a dilemma between two options. On one hand, there's res.cookie which utilizes the Express framework to set/read cookies on the server-side. On the other hand, there's d ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

Unable to utilize drop-down menu for input in form

I have created this drop-down menu using HTML: <div id="mySelect" class="select btn-group m-b" data-resize="auto"> <button style="font-weight:700;background-color:#fff;border-style:solid; border-width:2px" type="button" id="expiry_month" ...

I'm having trouble locating my JavaScript files while trying to render a dynamic webpage

My navbar is set up to link to a dynamic web page like this <li class="<%= title == 'Cryptofolio' ? 'navbar-item active' : 'navbar-item' %>"> <a class="nav-link" href="/cryptofolio/< ...

Adjusting the color of a cell based on its value

Currently, I am in the process of converting a CSV file to an HTML table by utilizing a tool available at . However, I am facing a challenge in modifying the background color of cells based on their values. I would greatly appreciate any help or guidance w ...

Retrieve the data attribute from the last three tag names using the Jquery Prev() method

Hi there! I'm currently trying to map out the route for going from clicking a button on the ADDtab_138269500 and then navigating back (to the previous) all the way to the first encountered span tag but in reverse order. If you want to view the code, ...

Deactivation within the directive does not entail a reset

Check out this Stackblitz In my Angular application, I implemented a Directive that disables a button after it's clicked to prevent double-clicking until a certain time has passed. <button appThrottleClick (throttleClick)="click()"> BUTTON & ...

Setting the default <a-sky> in Aframe: A step-by-step guide

There was a fascinating projection I witnessed where two images were displayed in the sky. [https://codepen.io/captDaylight/full/PNaVmR/][code] Upon opening it, you are greeted with two spheres and a default white background. As you move your cursor over ...