Unusual behavior when importing in Angular 2 using TypeScript

While working on a demo for another question on Stack Overflow, I initially used angular-cli and then switched to Plunker.

I noticed a peculiar difference in behavior with the import statement between the two setups.

The issue arises with the second import in the code snippet below:

moment.service.ts

import { Injectable } from '@angular/core';

// Works in Plunker setup
import m from 'moment';
// Works in angular-cli setup
// import * as m from 'moment';

@Injectable()
export class MomentService {
  moment = m;
}

In the angular-cli environment, I had to use:

import * as m from 'moment';

However, in the Plunker setup, whether running on Plunker or locally, I had to use the following for it to work in the browser:

import m from 'moment';

Can anyone explain this difference in behavior?

Plunker: Link

Github: Plunker code local version (includes a server.js for local hosting)

Github: Angular-cli version

Answer №1

Summary: Different demos use different module formats. In Plunker, the entire module is treated as a default export, while in the CLI project there is no default export.

The demos utilize varying module formats. The format used by the Plunker demo is unspecified, and it's unclear if SystemJS defaults to ES6. On the other hand, the CLI project employs the ES6 module format.

When the module format is AMD, CommonJS, or global, it exports the entire module as the default export, as outlined here. However, this is not the case with ES6 modules where you must explicitly define the default export, which moment.js does not do.

Hence, in the Plunker demo, `import m from 'moment'` works due to the configuration telling SystemJS and TypeScript to treat the whole module as the default export when none exists. Conversely, in the CLI project, since the module is not considered the default export, you need to use `import * as m from 'moment'`, instructing to import all named exports from moment under the 'm' namespace.

Here is a discussion on TypeScript's repository regarding this topic

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

What could be the reason for `process.env.myvariable` not functioning in a Next.js project with TypeScript

After creating a file called .env.local in the root directory of my project, I added a variable called WEBSOCKET_VARIABLE=THIS_IS_TEXT to it. However, when I try to access it using process.env.WEBSOCKET_VARIABLE, nothing is found. What could be causing ...

React: Function is missing a return type declaration. eslint plugin @typescript-eslint urges for explicit function return types

I'm just starting out with Typescript in React. I've created a simple functional component, but eslint is giving me an error saying that the return type for the functional component itself is missing. Can anyone help me figure out what I'm d ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

Get rid of the Modal simply by clicking on the X mark

Objective: The modal should only be closed by clicking the X mark and not by clicking outside of it. Challenge: I am unsure how to resolve this issue when using the syntax code [config]="{backdrop: 'static'}" Additional Information: I am new ...

The Angular build process was successful on a local machine, however, the Angular build failed when

I am facing a challenge with my Angular project that I want to deploy on Gitlab Pages. Initially, when I execute: ng build --prod locally, the build is successful. Below is my .gitlab-ci.yaml: image: node:8.12.0 pages: cache: paths: - node_mo ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

The type '{ domain: any; domainDispatch: React.Dispatch<any>; }' cannot be assigned to a type 'string'

Within my codebase, I am encountering an issue with a small file structured as follows: import React, { createContext, useContext, useReducer } from 'react' const initState = '' const DomainContext = createContext(initState) export co ...

Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables. Currently, I have a parent class that will eventually showcase a list of "QuestionComponents". The pertinent section of the parent class templat ...

Enhance your Typescript code by incorporating typing for response objects that include both index signatures and key-value pairs

I am grappling with how to properly incorporate typescript typings for the response object received from a backend service: { de49e137f2423457985ec6794536cd3c: { productId: 'de49e137f2423457985ec6794536cd3c', title: 'ite ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Unlocking 'this' Within a Promise

I seem to have an issue with the 'this' reference in the typescript function provided. It is not correctly resolving to the instance of EmailValidator as expected. How can I fix this so that it points to the correct instance of EmailVaildator, al ...

The use of 'import ... =' is restricted to TypeScript files

Error: Oops! Looks like there's a hiccup in the code... 'import ... =' is exclusive to TypeScript files. Expecting '=' here. Don't forget the ';'. Unexpected keyword or identifier popping up! package.json ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

The call stack size has reached its maximum limit due to running 2 Collection.find commands

I've encountered a Maximum call stack size exceeded exception in my Chrome console while working with Angular2 and Meteor. This issue started after I added the following code to my client side: var userChannelsId = UserChannels.find({idUser: Meteor.u ...

What is the process for importing a TypeScript module exclusively through typings without having to download it separately?

Currently, I am working on a widget for a website that is already utilizing jQuery and I am using TypeScript. The goal is to embed my output into the host website while taking advantage of the existing jQuery library loaded by the host site. In order to r ...

The correlation between methods in programming languages

Can a class or object be created with type constraints between methods? abstract class Example<T>{ abstract methodOne(): T abstract methodTwo (arg: T):any } I am looking to ensure that the argument of methodTwo is the same type as the return ty ...

Tips for inserting a row component into a table using Angular 7

I am currently using the latest version of Angular (7.2.0). I have created a custom tr component as follows: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-table-row', templateUrl: './table- ...

Using Typescript alongside Angular 1.6 and browserify for your development needs

Currently navigating the world of working with Angular types in TypeScript and bundling code using Browserify. After following a TypeScript guide related to Gulp, I utilized npm to install the Angular types and put together this simple ts file. import * a ...

Utilize generic typings to interact with the Array object

I'm facing a challenge in developing an interface that is dependent on another interface. Everything was going smoothly until I reached the Array of Objects. Let me elaborate, I have an 'Entity' that defines how a document is stored in a ...

Experiencing 429 Too Many Requests error on Angular 7 while attempting to perform multiple file uploads

Whenever I attempt to upload a large number of files simultaneously, I encounter an issue. The API interface only allows for the submission of one file at a time, requiring me to call the service for each individual file. Currently, my code looks like thi ...