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

Pattern matching for validating multiple email addresses

I need assistance with validating multiple email inputs using regex in Angular. I am looking to enforce a specific format for the emails, such as: Examples: *****@zigurat.com *****@test.com *****@partlastic.com The ***** can be any characters, but the ...

Unable to manipulate Bootstrap styles in Angular 7 application

Attempting to customize the styling of my breadcrumbs in an Angular App by removing the divider is proving challenging. I've referenced https://getbootstrap.com/docs/4.2/components/breadcrumb/#example, but unfortunately, it's not yielding the des ...

State mutation not reflected in input field value update

During the development of a small project for educational purposes, I encountered an issue with updating the input value. Below is the simplified component causing this issue. function TipSelector({selections, onTipChanged}: {selections: TipSelectorItem[], ...

Setting checkbox values using patchValue in Angular programming

I'm facing an issue with reusing my create-form to edit the form values. The checkbox works fine when creating a form, but when I try to edit the form, the values don't get updated on the checkbox. Below is the code snippet that I have been worki ...

Jest tests are failing because React is not defined

I am attempting to implement unit tests using Jest and React Testing Library in my code. However, I have encountered an issue where the tests are failing due to the React variable being undefined. Below is my configuration: const { pathsToModuleNameMapper ...

What is the best way to utilize RxJS for grouping data results, ordering them, and selecting specific items, while also retrieving data from the RxJS

Could you assist me in creating a query that groups by smileTypeId and counts rows by id, then orders by count in descending order and takes the top 2? Retrieve the Smiles array from the RxJS store. View Screenshot Get Post Smiles posts = [ { &quo ...

Finding a solution to this issue in Angular will consistently result in a false outcome

Can anyone explain why I keep getting the error message "This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap" whenever I try to compare charTypeEnum with ChartType.text? ...

Utilizing conditional date parameter in Angular's in-memory web API for an HTTP request

In my current project, there is a collection of objects referred to as members members = [ {id:'1', firstName:'John', lastName:'Black', birthDate:'1956-11-22', gender:'Male', email:'<a href="/c ...

Transferring Data from Angular Application to Spring Server via Rest Implementation

I am currently facing an issue while attempting to upload a file using Angular and send it to my Spring-based REST backend. I followed the guidance provided in this resource for my Angular service implementation. However, two problems have arisen: The fir ...

What strategies can I use to steer clear of the pyramid of doom when using chains in fp-ts?

There are times when I encounter a scenario where I must perform multiple operations in sequence. If each operation relies solely on data from the previous step, then it's simple with something like pipe(startingData, TE.chain(op1), TE.chain(op2), TE. ...

Using async-await in canActivate() within Angular 7

I am currently working on a code that verifies whether the browser contains user information. If not, the browser will make an API call to retrieve the user information from the server. Only users with valid information are granted access to navigate to di ...

Interface constructor concept

Trying to figure out how to dynamically add different types of components to a game object in TypeScript. After consulting the TypeScript documentation on interfaces, I discovered a unique approach for dealing with constructors in interfaces, which led me ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

What is the best way to refer to a specific argument by implication within a function type?

Is there a way to extract the name of an argument from one type and use it in another type? For example, is it possible to achieve something like this: type F_v1 = (name: number) => boolean; type A = ["name", number]; //type F_v2 = (A[0]: A[1]) => bo ...

I couldn't identify the Material import within the child modules of Angular 2

I am facing an issue with importing custom material.ts modules in my app.module.ts file. I am unable to use Material in components declared at the module root level. However, when I create a child module (ClientModule) and declare a component there, Materi ...

Discovering the position of an element within an array and leveraging that position to retrieve a corresponding value from a separate array

const STATE = ["TEXAS","CALIFORNIA","FLORIDA","NEW YORK"] const STATE_CODE = ["TX","CA","FL","NY"] With two arrays provided, the first array is displayed in a dropdown menu. The challenge is to retrieve the corresponding state code from the second array ...

Leverage Angular2 components within Angular4 framework

Would it be possible to utilize angular2 components in angular4 projects? Specifically, I am interested in using a chart generation library from . However, it seems that the dependencies of this library are not compatible with my application. Are angular2 ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

Add a calendar icon to the DateRangePicker in React Mui

I am trying to set up a DateRangePicker using Material UI with a calendar icon. Here is an example of how I want it to look: https://i.stack.imgur.com/LnYnY.png After following the API documentation and using this code: components={{ OpenPickerIcon: Cal ...