Utilizing moment.js in conjunction with typescript and the module setting of "amd"

Attempting to utilize moment.js with TypeScript 2.1.5 has been a bit of a challenge for me.

I went ahead and installed moment using npm :

npm install moment --save-dev

The d.ts file is already included with moment.js, so no need to install via @typings as usual. However, upon compiling my project, I encountered the following error :

Error TS2307: Cannot find module 'moment'.

To provide some context, here's a simple test case that I created to replicate the issue:

repro.ts file

import * as moment from "moment";
const date = moment().format("YYYY");
console.log(date);

tsconfig.json file :

{
    "compilerOptions": {
        "module": "amd"
    }
}

Upon trying to compile with:

.\node_modules\.bin\tsc

I received the aforementioned error. Interestingly enough, the compilation works fine if I target commonjs module (setting "module": "commonjs" in tsconfig).

What would be the correct approach to use moment when targeting amd module?

Answer №1

For your code to work properly, make sure to include "moduleResolution": "node" within the compilerOptions section of your tsconfig.json file.

If you don't specify the moduleResolution, it will default to classic unless the module is set to commonjs. This could be why your modules are not being found in the node_modules directory.

It seems that this issue may be addressed in an upcoming release of the compiler as mentioned here.

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

Challenges with using async await alongside synchronous functions

I'm currently navigating through a library that utilizes async functions and feeling a bit overwhelmed. I'm attempting to call a function that should return a string, but I'm hitting some roadblocks. As I understand it, the ZeroEx library fu ...

Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly? I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the ...

Why does Rollup insist on treating my dependency's TypeScript code as if it were written in JavaScript?

I've included an example code snippet here: https://github.com/thejohnfreeman/bugs/commit/b4ff15a670691ada024589693d22f4fd0abae08d The module called parent is primarily composed of type declarations written in TypeScript. The source entrypoint for Ty ...

Using arrays as props in React with Typescript

In my code, I have a Navbar component that contains a NavDropdown component. I want to pass an array as a prop to the NavDropdown component in order to display its dropdown items. The array will be structured like this: DropDownItems: [ { ...

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

I encountered an error in my Node.js application stating that it could not find the name 'Userdetailshistory' array. I am puzzled as to why this error is occurring and I suspect it may be due to my

import { Component, OnInit } from '@angular/core'; import { UserdetailshistoryService } from '../../services'; @Component({ selector: 'my-userdetailshistory', templateUrl: './userdetails-history.component.html', ...

"Implementing self-referencing mongoose models in Typescript: A step-by-step guide

I have a model: const message = new mongoose.Schema({ id: { type: ObjectId, required: true }, text: { type: String }, replies: [message] }); Looking to create a document structure like this: { "id": 1, "text": "Main Message", "replies": [ ...

Adding a fresh attribute to MongoDB using push model

I wrote a basic script that calculates the number of documents for a specific user and assigns it to externalUser.totalIcons. However, when I try to execute it, the model is not saved and the new property is not added to the database. My question is: wher ...

Tips for transferring the value of a text box between components bidirectionally in Angular 8

Let's create a scenario where we have two components: login and home. The goal is to capture the value entered in the text box of the login component and pass it to the text box in the home component when the "proceed" button in the login component is ...

Ensure that selecting one checkbox does not automatically select the entire group of checkboxes

Here is the code I'm using to populate a list of checkboxes. <label class="checkbox-inline" ng-repeat="item in vm.ItemList track by item.id"> <input type="checkbox" name="item_{{item.id}}" ng-value="{{item.id}}" ng-model="vm.selectedItem" /& ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

The p-calendar feature is experiencing compatibility issues with Internet Explorer, Edge, and Firefox

While I've had success using primeng p-calendar on Google Chrome, I've encountered an issue where the date-picker does not open upon clicking the text box on other browsers. Below is the snippet of HTML code I utilized: <p-calendar [(ngModel ...

What could be causing the transparency of my buttons when viewed on my device?

Recently, I customized the appearance of buttons in my App by adding colors. Surprisingly, everything looks perfect when I test it on a local server on my PC. However, once I deploy the App to my Android device, all the buttons become transparent. In my v ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

Utilize the forEach method with a TypeScript wrapper class containing a list

After replacing a list with a wrapper class that allows for monitoring changes to the list, I noticed that I can no longer use the forEach statement to iterate over the class. let numberList = new EventList<number>([1,2,3,4]); numerList.forEach((elem ...

What are the steps to setting up a basic Material UI Select component with React and Typescript?

I'm struggling to make the most basic Material UI Select work in React using Typescript. After spending three hours searching, I couldn't find an example that clearly explains how to set the label or placeholder for the Select component (I review ...

Exploring the implementation of custom global declaration in the latest version of NextJS, version

Looking to implement custom global declaration in NextJS In my NextJS project, I've defined a global prototype for String as shown below utils.d.ts export {} declare global { interface String { /** * Returns string after removing all htm ...

Invoking a function from a collection of mixed data types

I have established a mapping for a discriminated union consisting of different types, each linked to a corresponding function that uses a member of the union as a parameter: export interface Truncate { type: 'truncate' maxLength: number } ex ...

The parameter of type 'void' cannot be assigned to the parameter of type 'PathParams'

Established the route handler and encountered an issue while integrating it into my route. import {Application, NextFunction} from 'express'; import {container} from 'tsyringe'; const routeConstantsArray = { }; const constants: any ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...