The TypeScript error "Uncaught ReferenceError: require is not defined" occurs when the

When attempting to export a namespace from one .ts file and import it into another .ts file, I encountered an error:

NewMain.ts:2 Uncaught ReferenceError: require is not defined
. As someone new to TypeScript, I am still in the learning process. Below is a snippet from my tsconfig.json file:

{
 "compilerOptions": {
     "module": "commonjs",
     "noImplicitAny": true,
     "removeComments": true,
     "preserveConstEnums": true,
     "sourceMap": true
 },
 "files": [
     "greeter.ts",
     "Main.ts",
     "RajIsh.ts",
     "NewMain.ts"        
  ],
 "exclude": [
    "node_modules"
  ]
}

In my NewMain.ts file, I attempt to import a namespace:

 import {DepartmentSection} from "./RajIsh"
 class Employee{
     name: string;
     
     Display(username:string)
     {
         this.name=username;
         console.log(this.name);
     }
 }
 var person = new Employee();
 var itCell= new DepartmentSection.ITCell("Information Technology Section");
 console.log("Displaying from NewMain.ts by importing......");
 console.log(person.Display("XYZ")+" belongs to "+  itCell.DisplaySectionName("Finance Revenue and Expenditure Section"));
 console.log("Wooooooooo Hurrey!!!!!!!!!!!!!!!......");

The RajIsh.ts file contains the namespace:

 export namespace DepartmentSection {
    export class Section  {
        name: string;

        constructor(theName: string) {

                this.name = theName;
            }
        
        Department(depatmentName: string = "") {
            console.log(`${this.name} ,  ${depatmentName} !!`);
        }

    }

    export class ITCell extends Section{
        constructor(SectionName: string) { 
            super(SectionName); 
        }
        DisplaySectionName(DepartmentName:string) {
            console.log("Printing Section name...");
            super.Department(DepartmentName);
        }

    }
     export class LoanAndAccount extends Section {
        constructor(SectionName: string) { 
            super(SectionName); 
        }
        DisplaySectionName(DepartmentName:string) {
            console.log("Printing another Section name...");
            super.Department(DepartmentName);
        }
    }

 }

I have tried using

import DepartmentSection = require('./RajIsh');
, but when trying to access the classes and functions, I receive the error
Property 'ITCell' does not exist on type 'typeof' RajIsh
. What steps should I take next?

Answer №1

A while back, I encountered a similar issue and managed to resolve it using SystemJs. To work with it, try installing SystemJs via the command line with npm by running npm install systemjs, then implement it in your Index.html file within the head section like so:

<script src="node_modules/systemjs/dist/system.js"></script>

 <script>
    SystemJS.config({
    baseURL:"/", //You can specify the path for example /script and the browser will search inside the script folder
    packages:{
        ".":{
            defaultExtension:'js'
        }
    }
  })
  SystemJS.import("./main.js")
 <script>

Give this a try, it should work for you. Let me know if you need further assistance.

Answer №2

When utilizing the typescript compiler to merge your .ts files into a single main.js file, there is no requirement for using import and export.

require and import are only effective when employing a module bundler - they are not inherent in typescript!

You have the option to employ namespace for structuring your code, but it is not compulsory.

file thing.ts

namespace Test {
    class Thing {
    }
}

file app.ts

namespace Main {
    class App {
        constructor(){
             // A new Thing instance can be created here without any need for import!
             let n = new Test.Thing()
        }
    }
}

This method functions because the namespaces exist within the global scope, allowing them to be accessed from any location. However, module bundlers such as webpack maintain the privacy of your code (not accessible in the global scope), hence necessitating the use of import and export with webpack.

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

Wait until the document is fully loaded before importing npm in ReactJS/Next.js applications

Recently, I encountered an issue while trying to utilize a small js library named float-sidebar.js. After installing the module through npm, I realized that in React, it was throwing an error stating "window" is not defined. This problem arose because the ...

The error message "gulp error - _.flattenDeep is not a function when using gulp.watch" is indicating

Whenever I run a watch task, why am I encountering the TypeError: _.flattenDeep is not a function error? Below is the content of my gulpfile.js : var gulp = require('gulp'); var sass = require('gulp-sass'); var sourcemaps = require(&a ...

The member 'pipe' is not found within the 'AngularFireObject<{}>' type

As someone new to Angular, I've been following a tutorial by Mosh Hamedani on version 6 of Angular, but unfortunately the tutorial is based on version 4. Currently, I'm working on an e-commerce project that involves implementing an AddToCart butt ...

Volar and vue-tsc are producing conflicting TypeScript error messages

During the development of my project using Vite, Vue 3, and TypeScript, I have set up vue-tsc to run in watch mode. I am utilizing VS Code along with Volar. This setup has been helpful as it displays all TypeScript errors in the console as expected, but I ...

How come my uploaded Excel Javascript add-on opens in an external browser instead of the task pane?

Note: It has come to my attention that I must save the taskpane.html file on my local drive before it opens in an external browser. This detail slipped my notice last week. I am currently developing a Javascript, or rather Typescript, API add-in for Excel ...

Encountering an npm issue while attempting to install @angular/cli

While trying to install Angular on Debian10, I encountered an error message: https://i.sstatic.net/mVeTH.png It appears that the npm version is outdated. In an attempt to resolve this, I used the following command to update npm to the latest version: npm ...

Utilizing Typescript with tfjs-node to effectively integrate the node-gpu version with regular node functionalities

I am facing challenges while running my Tensorflow.js node application with and without the GPU library. In vanilla JavaScript, examples show using require() for either @tensorflow/tfjs-node or @tensorflow/tfjs-node-gpu. However, in my TypeScript setup, I ...

Running Handlebars using NodeJS can sometimes result in a "Cannot find module './parser'" error

After successfully creating and implementing a Handlebars template in the Browser, my next goal is to utilize the Handlebars precompiler, which requires a NodeJS module. I have already downloaded Handlebars for NodeJS along with all dependencies locally (n ...

I'm curious about the origins of the "readme" field within the artifact registry file

Within our private npm registry on Azure, we house our own npm package alongside the npmjs packages. One particular package, @typescript-eslint/parser, has caused our pipelines to fail during the npm install task due to a SyntaxError: Unexpected end of JSO ...

Running cypress tests with regression or smoke tags within nx workspace is a straightforward process

I have a cypress project set up and I am trying to run cypress tests based on tags using the nx command. cypress grep--->"@cypress/grep": "^4.0.1" After applying the nx command like this: nx run e2e:e2e --tags=@regression The issu ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

What might be causing the component in Angular and TypeScript to have trouble reading the data returned by the service?

I've been working on this for hours without success. I created a web API get method that returns a simple array. public Hero[] getHeroes() { return new Hero[] { new Hero { Id = 1, Name = "Hunain Hafeez-1" }, ...

Converting an object within an object into an Angular Class (Type)

Is there a way to convert the value of obj.category into the Category type as shown in the example below? I specifically need this conversion in order to select options in a dropdown. export class Category{ id: number; name: string; construc ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Running npm install does not automatically install dependencies that are nested within other dependencies

npm install is encountering issues with installing nested dependencies beyond a depth of 2 packages. My suspicion is that certain dependencies, like bcrypt, are causing errors during installation and terminating the npm process, even though they appear to ...

Has this package been properly registered on npm?

UWS is no longer supported, but you can now install μWebSockets by following these steps: npm install uNetworking/uWebSockets.js#v15.10.0 If you encounter issues when trying to update your packages with npm update, you might receive the following errors ...

What is the best choice for storing data in my Angular2+ component: an object or an observable?

If I were to create an angular2+ component that fetches data from an API and displays its name, which approach would be considered more idiomatic? Initial Strategy: Using thing as an object In this scenario, the component subscribes to a websocket observ ...

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...

Dependency injection in Angular 2 service not functioning as expected

I am facing an issue while trying to retrieve static data from UserService in Angular 2. Although everything seems correct based on the documentation, it is not functioning as expected. Below is my UserComponent.ts import {Component ,OnInit } from ' ...