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

Having trouble sending an image to the API endpoint using Angular 6 reactive form

Currently utilizing Angular 6 along with Reactive Form The task at hand involves uploading a user avatar image, which led to the creation of a change-avatar component containing the code provided below. import {Component, OnInit, ViewChild} from '@a ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

Getting rid of Glyphicons in Laravel 5.4

I am currently working on a project using laravel-5.4 and I need to remove Glyphicons from it. To achieve this, I executed the following command from the root folder of my project: npm uninstall glyphicons-halflings After running npm run production, the ...

Conceal the header on signup and login pages using Material UI

I am working on a project with three pages: SignUp, Login, and Lists, along with a header component. My goal is to hide the header on the SignUp and Login pages, and only show it on the List page. Any suggestions on how I can achieve this? Here is my cod ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

Having trouble locating modules or properties with ANTLR4 TypeScript target?

Having reached a frustrating impasse, I am seeking assistance with a perplexing issue. My attempt to integrate TypeScript with ANTLR4 has hit a snag, and despite exhaustive efforts, I am unable to pinpoint the root cause (with limited documentation availab ...

I have a component that I utilized for subscription purposes. After subscribing to the method, I ensured to properly unsubscribe in order to prevent any memory leaks

Access code for services private postsData: Post[] = []; private updatedPosts = new Subject<Post[]>(); getPosts() { return [...this.postsData]; } getUpdatedPostsListener() { return this.updatedPosts.asObservable(); } addNe ...

When navigating to a new component using routerLink in Angular, the previous component is also loaded. This

I am facing an issue with my sign-in page and sign-up button. When the button is clicked, it should route to /sign-up. My expectation is that only the sign-up component should be displayed on the /sign-up page, but in reality, both the sign-up and sign-in ...

Troubleshooting Problem with Uploading Several Photos to Firebase Storage

I need assistance with uploading multiple photos to Firebase Storage. Despite my efforts, it seems that the original upload keeps getting overwritten and the folder with the venueID property is not being created. Can someone provide some guidance on this i ...

Issue encountered when trying to pass a string into URLSearchParams

const sortString = req.query.sort as string const params = Object.fromEntries(new URLSearchParams(sortString)) Upon moving to the implementation phase, I encountered: declare var URLSearchParams: { prototype: URLSearchParams; new(init?: string[][] ...

Error encountered: YouCompleteMe is unable to locate the necessary executable 'npm' for the installation of TSServer

While attempting to install YouCompleteMe for vim and enable support for Java and Javascript, I followed the instructions provided here. My command was: sudo /usr/bin/python3.6 ./install.py --java-completer --ts-completer Unfortunately, I encountered an ...

Issue occurred while trying to deploy Firebase functions following GTS initialization

Objective: I am aiming to integrate Google's TypeScript style guide, gts, into my Firebase Functions project. Desired Outcome: I expect that executing the command firebase deploy --only functions will successfully deploy my functions even after init ...

Ionic 2 encountering issue with `ctorParameters.map` not being a function error

Recently, I wanted to incorporate the Network-information plugin into my project but encountered compatibility issues with an older version of Ionic-native. To resolve this, I took the following steps: npm rm --save ionic native npm install --save ionic-n ...

Implementing a custom type within a generic function

Struggling with a particular problem, I am trying to figure out whether it is possible to pass a custom type or if only native TypeScript types (such as string and number) can be passed into a generic type implementation for an interface: type coordinates ...

Unable to set a breakpoint within Angular constructor or OnInit method

I am currently facing an issue with my Angular application where breakpoints set in F12 tools in Chrome or IE are not working. I have a simple test case below: export class LoginComponent implements OnInit { message: string; constructor(private r ...

Angular 7 navigation successfully updates the URL, but fails to load the corresponding component

Despite exhausting all other options, I am still facing a persistent issue: when trying to navigate to a different component, the URL changes but the destination component fails to load. Explanation: Upon entering the App, the user is directed to either ...

The Angular HTTP post request fails to get sent

I have a simple post method defined as follows: createTask(taskName: String, parentTaskId: String) : Observable<any>{ let headers : HttpHeaders = new HttpHeaders(); headers.set('Content-Type', 'application/json; charset=utf-8&a ...

Utilizing Angular 2 and appengine with Python to successfully pass a basic GET request

I am currently attempting to run Angular 2 on the front end and App Engine Python on the back end. To achieve this, I have launched the App Engine Python backend server using dev_appserver.py --port 3030 app.yaml, and the Angular 2 frontend server using "n ...

There is no record of the property's history

I am embarking on a fresh project utilizing React and TypeScript. One of the hurdles I have encountered is with the Router. Strangely, TypeScript does not recognize the history property, even though it should be accessible as mentioned in the documentation ...

When attempting to navigate using router.navigate in Angular 6 from a different component, it triggers a refresh

My routing setup is structured as follows: Main App-routing module const routes: Routes = [ { path: '', redirectTo: environment.devRedirect, pathMatch: 'full', canActivate: [AuthenticationGuard] }, { path: &a ...