Redeclaring block-scoped variable is not allowed

I have a Node program that primarily uses CommonJS, causing my JS files to begin with several require statements. To transition into TypeScript gradually, I decided to rename these JS files to TS. However, I encountered the following errors:

https://i.sstatic.net/wwXOn.png

Here is an example of the code:

const RSVP = require('rsvp');
const moment = require('moment');
const firebase = require('universal-firebase');
const email = require('universal-sendgrid');
const sms = require('universal-twilio');
const merge = require('merge');
const typeOf = require('type-of');
const promising = require('promising-help');
const _ = require('lodash');

const up = require('./upload');
const audience = require('./audiences');
const message = require('./messages');

The locally referenced modules like upload, audiences, and messages probably define most (if not all) of the same modules such as lodash. It appears that the namespace scope might not be respected between modules, but the reason for this is unclear.

I am also uncertain whether using ES6 import syntax would successfully transpile into ES5 as a "require" module format in CommonJS (since it involves Node 0.10.x).

As additional context, here is my tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "removeComments": true,
    "sourceMap": true,
    "outDir": "./dist",
    "watch": true
  },
  "compileOnSave": true
}

Note: I have come across instances where people received the error "cannot redeclare block-scoped variable", but none of those discussions seemed completely relevant to my situation. Since I am relatively new to TypeScript, there's a possibility that I'm making a rookie mistake.


Additionally, I observed some examples of an unusual combination of CommonJS and ECMAScript module formats:

import up = require('./upload');

This differs from my usual approach:

const up = require('./upload');

However, when using the "import" keyword, it raises an issue stating that upload.ts is not recognized as a module:

https://i.sstatic.net/52uxQ.png

Answer №1

Upon examining the current version of moment.d.ts on DefinitelyTyped, it is evident that it functions as a global script file (as opposed to a module) containing a variable named moment:

declare var moment: moment.MomentStatic;

This status as a global script file stems from its lack of import or export statements.

Your own file is currently categorized as a script file as well. This may seem misleading, but TypeScript does not inherently recognize require as an import statement. In essence, require could be interpreted as any other function.

To address this, a specific syntax must be utilized:

import moment = require("moment");

This directive explicitly informs TypeScript that an import operation is taking place, facilitating the transformation into imports compatible with CommonJS, AMD, UMD, SystemJS, and so forth.


In relation to TypeScript 2.0, revisions have been made to ensure that these .d.ts files are no longer classified as global script files; instead, they are now authored as modules. By examining the declaration files for moment in the types-2.0 branch on DefinitelyTyped, you will encounter the following lines:

declare var moment: moment.MomentStatic;
export = moment;

The statement export = moment serves as a module system-agnostic representation of module.exports = moment.

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

Leverage async and await features in TypeScript aiming at ES5 compatibility

Currently working on a TypeScript project that is set to target ES5, I am exploring the feasibility of incorporating async/await functionality. Syntactically, the TypeScript compiler is able to transpile the code without issues. However, it has come to my ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

Webpack is mistakenly looking in the incorrect subfolder when attempting a relative import

I have set up a Vue application (version 3 with TypeScript) within a directory structure where the Vue app is nested inside a directory named /my-vue-app. In the same directory, there is a folder containing my Node.js server code (not TypeScript) that I am ...

What could be the root of this next.js build issue occurring on the Vercel platform?

I recently upgraded my next.js project to version 12.0.7, along with Typescript (4.5.4) and pdfjs-dist (2.11.228), among other libraries. Locally, everything runs smoothly with the commands yarn dev for development and yarn build for building. However, af ...

Is there a way to ensure that the onChange event of ionic-selectable is triggered twice?

I've been working with an ionic app that utilizes the ionic-selectable plugin, and for the most part, it's been running smoothly. However, I encountered a rare scenario where if a user on a slow device quickly clicks on a selection twice in succe ...

Vue component prop values are not properly recognized by Typescript

Below is a Vue component I have created for a generic sidebar that can be used multiple times with different data: <template> <div> <h5>{{ title }}</h5> <div v-for="prop of data" :key="prop.id"> ...

What is the best way to pass only the second parameter to a function in TypeScript?

Let's consider a TypeScript function as shown below: openMultipleAddFormModal(commission?: Commission, people?: People): void { // some data } To make a parameter optional, I have added the Optional Chaining operator. Now, how can I modify the code ...

The program is requesting an expression involving the user's username

https://i.stack.imgur.com/tf1QD.png What is causing the issue with trying to use user.username? as an expression? While user.username returns a string of the User's username, I am unable to index it into listOfPlayers[]. client.on("messageReacti ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

Excluding CommonJS libraries from the production build using Webpack in Vue-cli is a helpful strategy to optimize your application

Successfully implemented this for vue using the Webpack config externals Started by adding the Vue CDN to my HTML file index.html <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

Creating OpenAPI/Swagger documentation from TypeScript code

I am in search of a solution to automatically create OpenAPI/Swagger API definitions based on my Node.JS/Express.JS/Typescript code. It would be perfect if I could simply add annotations to my Express Typescript base controllers and have the OpenAPI/Swagg ...

What is the process of converting a `typeorm` model into a GraphQL payload?

In my current project, I am developing a microservice application. One of the services is a Node.js service designed as the 'data service', utilizing nestjs, typeorm, and type-graphql models. The data service integrates the https://github.com/nes ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Invoke the Organize Imports function using code and then proceed to save the updated file automatically

My current task involves: async function doItAll(ownEdits: Array<TextEdit>) { const editor: TextEditor = await getEditor(); applyOwnChanges(editor, ownEdits); await commands.executeCommand('editor.action.organizeImports', ...

Unique custom data type for an array of objects

My collection consists of objects that share a common structure: type Option = { label: string value: string | number | null } type ElementObject = { id: string options: Option[] } type ElementArray = ElementObject[] const array: Element ...

Tips for updating ion-select option to correspond with the object by utilizing the object's identifier as the value

In my code, I have a select element that looks like this. <ion-select formControlName="location" (click)="clearSectionAndTask()"> <ion-select-option *ngFor="let location of locations" value="{{location.locationId}}"> ...

Optimal approach for designing interfaces

I have a situation where I have an object retrieved from the database, which includes assignee and author ID properties that refer to user objects. As I transform a number into a user object, I am unsure about the best practice for defining the type of the ...

Using TypeScript conditional types with extends keyof allows for checking against specific keys, but it does not grant the ability

In TypeScript, I created custom types using template literal types to dynamically type the getters and setters of fields. The types are structured like this (Playground Link): export type Getters<T> = { [K in `get${Capitalize<keyof T & strin ...

Is it possible to create a .d.ts file to easily share constants between JavaScript and TypeScript?

Currently, I am in the midst of a node.js project that involves both TypeScript and JavaScript due to historical reasons. My goal is to establish project-wide constants that can be utilized in both languages. Initially, I thought about creating a .js file ...