Attempting to redeclare a previously exported variable will result in an error stating: "Cannot

I'm currently facing an issue with a npm module located in a different directory that I've linked to another project using npm link. Despite successfully compiling the typescript, when I try to import the module and use its function, I encounter multiple errors. Below is the tsconfig for the npm module:

{
    "compilerOptions": {
      "target": "es5",
      "module": "commonjs",
      "declaration": true,
      "outDir": "./lib",
      "strict": true,
    },
    "include": ["src"],
    "exclude": ["node_modules"]
}

The index.ts file of the module looks like this:

import * as APIServices from "./API/API"
import APIPage from "./API/APIPage"

export { APIServices, APIPage }

Here is how I'm attempting to utilize the package:

import APIServices from 'common-backend'

console.log(APIServices)

However, upon running the file, I encounter the following errors:

TSError: ⨯ Unable to compile TypeScript:
../../common-backend/lib/index.js:3:1 - error TS2323: Cannot redeclare exported variable 'APIPage'.

3 exports.APIPage = exports.APIServices = void 0;
  ~~~~~~~~~~~~~~~
...

...

The errors are being thrown on the index.js file which contains the following code:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIPage = exports.APIServices = void 0;
var APIServices = require("./API/API");
exports.APIServices = APIServices;
...

...

...

Could this be a configuration issue in the tsconfig? Or perhaps an error in the way imports and exports are handled? I've explored various possibilities but haven't been able to find a solution yet. Any help or insight would be greatly appreciated.

Edit: I neglected to include the API class being imported:

import { Validators } from "./Validators"
import { APIRoute, Config } from "./helpers/Interface"
import { Router } from "express"
const router = Router()

class API {
...
...

...

}

export { API, Validators, router }

Answer №1

It's possible that your issues won't be completely resolved by this solution, but it appears that there may be errors in your imports. There are a couple of different methods for handling imports.

export default APIServices

After doing so, you can import as follows:

import APIServices from 'common-backend'

If you wish to export multiple named entities as demonstrated below:

export { APIServices, APIPage }

You will need to import them using one of the following two approaches:

import { APIServices } from 'common-backend'

Alternatively, you could try something like the method shown below, although I am not as familiar with it since I personally prefer importing only what is necessary:

import * as CommonBackend from 'common-backend'
// then use CommonBackend.APIServices

Answer №2

After some investigation, I discovered that the problem stemmed from my reliance on ts-node to compile and execute the project's code with the package. By replacing

node --inspect -r ts-node/register src/app.ts"
with node ./dist/src/app.js, all issues were resolved. However, the exact factors affecting the proper execution of the JavaScript remain unclear.

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

Tips for Implementing Error Handling in Angular using Sweetalert2

On this code snippet, I have implemented a delete confirmation popup and now I am looking to incorporate error handling in case the data is not deleted successfully. confirmPopUp(){ Swal.fire({ title: 'Are You Sure?', text: 'Deleti ...

Update to the newest Node version on Windows using npm

I'm encountering an issue while trying to update Node.js to the latest version on my machine. When I run the following commands through npm, I receive the error below: npm install -g n This is the error I encountered: npm ERR! code EBADPLATFORM npm ...

What steps should I take to incorporate a timer into my bot similar to the timer used by other giveaway bots

I am looking to add a timer to my bot giveaway embed message that continues to update itself even when the bot is offline, without showing that the message was edited. Here's what I currently have in my embed: const embed = new MessageEmbed(); ...

typescript: exploring the world of functions, overloads, and generics

One interesting feature of Typescript is function overloading, and it's possible to create a constant function with multiple overloads like this: interface FetchOverload { (action: string, method: 'post' | 'get'): object; (acti ...

What are the limitations of jest and jsdom in supporting contenteditable features?

I am facing an issue with a particular test case: test('get html element content editable value', () => { // arrange const id = 'foo'; document.body.innerHTML = `<div id='${id}' contenteditable="true">1</div ...

The aggregation pipeline in nodeJS with mongoDB is failing to return any results, returning an empty array instead

Currently, I am enrolled in Jonas Schmeddtman's Node.js course where I am working on developing a tour App. However, I have encountered an issue where sending a request via Postman on the specified route results in an empty array instead of the expect ...

Tips for managing and capturing errors in Express

const database = require('database'); const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors()); const bodyParser = require('body-parser'); const urlencodedParser = body ...

Searching for two distinct nested key values in Ramda

I am new to Ramda and wondering if it is possible to retrieve two different key values at the same level of an object. Below is the code I have added: In this scenario, the object 'list' contains keywords 'users' and 'employee&ap ...

Creating dynamic components with constructor parameters in Angular 9

Having trouble passing a value to the constructor in the component generation code. Check out the original code here: https://stackblitz.com/edit/angular-ivy-tcejuo private addComponent(template: string) { class TemplateComponent { @ViewChild( ...

Is there a way to add zeros at the beginning of ZIP codes that have only 3 or 4 digits using LODASH or Typescript?

Looking at the JSON data below, it includes information on USPS cities, states, counties, latitude, longitude, and zip codes. With over 349,000 lines of data, it's very extensive. ... { "zip_code": 988, "latitude": 18.39 ...

Is there a way to retrieve my environment variable prior to initializing the server in Next.js?

I have chosen to utilize vault services for safeguarding my confidential information. In order to ensure security, I must execute the vault script (node fetch-vault-secrets.js) prior to initiating the following build and development commands. view image ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Exploring the Power of TypeScript with NPM Packages: A Comprehensive Guide

I am working with a "compiler" package that generates typescript classes. However, when I attempted to run it using npm, an unexpected error occurred: SyntaxError: Unexpected token export To avoid the need for compiling local files, I do not want to con ...

Using `Grunt --force` results in a node error: incorrect option chosen

I am encountering an issue with my Grunt task named eslint:jenkins which is responsible for running eslint on the project. In the build pipeline, I execute it using the following command: grunt eslint:jenkins --force --verbose To prevent the grunt from f ...

Exploring React JS Subdomains

I have been developing a MERN application that needs to support dynamic subdomains for each company, like companyname.localhost. In order to make this work, I made an adjustment in my .env file with the line: DANGEROUSLY_DISABLE_HOST_CHECK=true After a us ...

What are the ways to expand the maximum call stack size in a Node.js environment?

This particular question stands out from other inquiries regarding a Node error message that states RangeError: Maximum call stack size exceeded. I am well aware of why this error message occurs - it's due to excessive recursion on my end. Thank you ...

In the CallableFunction.call method, the keyword "extends keyof" is transformed into "never"

In the following method, the type of the second parameter (loadingName) is determined by the key of the first parameter. (alias) function withLoading<T, P extends keyof T>(this: T, loadingName: P, before: () => Promise<any>): Promise<void ...

How to Set Up Bower in WebStorm

I require assistance with the installation process of bower in WebStorm. My current version is 11.0.2 and I have a package.json file that needs to include bower.json for implementing a date-picker in Angular.js. To achieve this, I need to install bower. Th ...

Issue encountered during installation of [email protected] on a Windows 10 operating system

Encountered an error during the installation of [email protected] on a Windows 10 system. npm ERR! code ETARGET npm ERR! notarget No matching version found for <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee998b8cddc38d8 ...

What is the method to retrieve body in express.js GET call?

When using sails.js framework, which internally utilizes express.js, I encountered an issue while sending a body in a GET request. The command I used was: curl -u username:password -i -H "Accept: application/json" -X GET -d "msisdn=32323" http://localhost ...