Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when running npm start:

"NetworkError: 404 Not Found - http://localhost:3000/node_modules/moment/" /node_m...moment/ Error: patchProperty/desc.set/wrapFn@http://localhost:3000/node_modules/zone.js/dist/zone.js:769:27 Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:356:24 Zonehttp://localhost:3000/node_modules/zone.js/dist/zone.js:256:29 ZoneTask/this.invoke@http://localhost:3000/node_modules/zone.js/dist/zone.js:423:29
Error loading http://localhost:3000/node_modules/moment as "moment" from 'my file'

Various attempts have been made to import moment.js with no success, including:

import * as moment from 'moment'

and

import * as moment from 'moment/moment.d'

However, these methods still result in errors. My SystemJs map property includes:

 var map = {
    'app':                        'app', // 'dist',
    '@angular':                   'node_modules/@angular',
    'services':                   'app/service',
    'moment':                     'node_modules/moment',//moment.js
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
 };

Attempts to install typings also faced issues:

Typings for "moment" already exist in "node_modules/moment/moment.d.ts". You should let TypeScript resolve the packaged typings and uninstall the copy installed by Typings

After troubleshooting this, I encountered the error:

typings ERR! message Unable to find "moment" ("npm") in the registry.

Is there a solution to overcome this dilemma?

Answer №1

To start off, the first step is to download and install the moment package using npm:

npm install moment --save

Next, make adjustments to your systemjs configuration file (2 lines):

(function (global) {
  // Specify where the System loader should search for modules
  var map = {
    'app': 'app', // 'dist',
    '@angular': 'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs': 'node_modules/rxjs',
    'moment': 'node_modules/moment', <== include this line
  };
  // Define how to load modules with no filename or extension
  var packages = {
    'app': { main: 'main.js', defaultExtension: 'js' },
    'rxjs': { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
    'moment': { main: 'moment.js', defaultExtension: 'js' } <== include this line
  };

Now you are able to utilize it in your code:

import * as moment from 'moment';

You can find type definitions at node_modules/moment/moment.d.ts

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

Navigating the pathway to retrieving variables within an Angular Component function

export class MapsComponent implements OnInit { @ViewChild('googleMap') gmapElement: any; map: google.maps.Map; data = "initialised"; ngOnInit() { var directionsService = new google.maps.DirectionsService; ...

Tips for utilizing the latest hook feature in Typegoose

After adding a pre hook on updateOne events, I noticed it functions differently compared to save events... I believe this discrepancy is due to the fact that the update command typically includes a matcher as its first argument. I attempted to capture the ...

Error message "auth/code-expired" is triggered when Firebase Multi Factor Authentication for a web application detects that the verification code has expired

While working on adding multi-factor authentication to my Angular web application, I encountered an error message stating: "auth/code-expired", "The SMS code has expired. Please resend the verification code to try again.", even though I ...

After setting up yarn globally on my Ubuntu 20 VPS, I encountered an error message when attempting to run the command. The system returned a message stating that the command 'yarn

Here are the commands I used to install yarn: curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - sudo apt-get install -y nodejs npm install -g yarn After installation, running 'yarn -v' results in Command 'yarn' not found. ...

The npm installation encountered an error with the command 'bower install' and exited with error code 1

I am looking to develop widgets for the XBee ZigBee Cloud Kit. In order to get started, I need to set everything up properly. I have been following this guide. After facing issues with the automated setup, I decided to proceed with the manual setup. I su ...

Typescript: create a type similar to keyof but with a particular value type

I have an interface called MyInterface interface MyInterface { field1: boolean, field2: MyType, field3: MyType } In this interface, I want to create a new type that contains only the keys which have values of type MyType. While I know about the key ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

Utilizing TS2722 alongside restrictive parameters in tsconfig

I have encountered these errors due to the presence of the strictNullChecks parameter, which is activated by the strict configuration in the tsconfig.json file. It appears that when arguments.length === 2, the ab function should be available (thanks to Fun ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Angular2: using the #ngFor directive to assign a value to a component field

Here's a component I'm working with: @Component({ selector: "expenses-component", templateUrl: "expenses.html" }) export default class ExpensesComponent { private expenses: [] = [{name: "Foo", amount: 100}, {name ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition: function myFunc( id: string, optionalParamOne?: number, optionalParamTwo?: string ) { console.log(optionalParamTwo); } If I want to call this function and only provide the id and optionalParamTwo, without need ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

Beautylog has been causing problems with gulp-typings

Everything was running smoothly until today, but now we have encountered an issue with a dependency of gulp-typings conflicting with an update to the beautylog dependency in our TypeScript solution. I've attempted to troubleshoot by reinstalling and u ...

What is the best way to confirm that a certain element is not present on the page using playwright?

My current challenge involves testing a website that features a logo, and I need to ensure that the logo does not display on specific pages. I have been exploring the Playwright assertions documentation for guidance on how to assert that an element does N ...

I am sometimes experiencing issues with activating ajax code using Bootstrap 3 modal

I'm stumped trying to find a solution for this issue. Currently, I am utilizing the bootstrap modal to retrieve ajax content from a specified URL. To prevent content overlap, I am using $.removeData() when reloading the content. The problem arises w ...

Error: Unable to iterate over data.data due to its type

I am attempting to fetch images from the woocommerce API and here is the code I am using: this.config.getWithUrl(this.config.url + '/api/appsettings/get_all_banners/?insecure=cool') .then((data: any) => { this.banners = data.data; consol ...

Insert items into an array at a specific index in typescript

Using the map function, I am adding elements to array arr1. Is there a way to specify the starting index position in typescript? For example: If I want to add elements from the 3rd index position of the array, with the first two indices holding a value of ...

What is the best way to recycle a single modal in Ionic?

Apologies for the vague title, but I'm facing an issue with creating a single modal to display data from multiple clickable elements, rather than having separate modals for each element. For example, when I click on item 1, its data should be shown in ...

Top method for changing Enum to Set in TypeScript

Take a look at the enum below: enum Animes { OnePiece = 'One Piece', Naruto = 'Naruto', Bleach = 'Bleach' } How can we efficiently transform this enum into a Set? ...