I am unable to simply import lodash.add into my Angular 4 project

I'm struggling to import the add method from the lodash library using Angular 4 and TypeScript.

I've attempted various approaches:


import { add } from 'lodash';
import { add } from 'lodash/add';
import * as add from 'lodash/add';
import { add } from 'lodash.add';
import * as add from 'lodash.add';

(and possibly more that I can't recall)

Here is my latest (perhaps desperate?) attempt at accomplishing this:


import { Component, OnInit } from '@angular/core';
import add = require('lodash.add');

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  private x: number;

  constructor() { }

  ngOnInit() {
    let y = add(5, 5);
  }

}

Unfortunately, it's not working.

When I run "ng serve," I receive the following error message:

ERROR in ...test.component.ts (2,1): Import assignment cannot be used when targeting ECMAScript 2015 modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.)

Here is my package configuration:

{
  "name": "treeshake",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    // Other dependencies...
  },
  "devDependencies": {
    "@angular/cli": "1.0.0-beta.32.3",
    // Other dev dependencies...
  }
}

and my tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es2016",
      "dom"
    ],
    "mapRoot": "./",
    "module": "es2015",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  }
}

Answer №1

My recommendation is to utilize lodash-es, a version of lodash that disperses each function as an individual ECMA Script module. When importing only the necessary code for the add function, you can do so like this:

import add from 'lodash-es/add'

Additionally, there is a dedicated @types/lodash-es package available to replace @types/lodash.

Answer №2

The entry in your package.json is incorrect. Please fix the typo

@types/lodash": "lattest",

You should import lodash like this:

import * as _ from 'lodash';

Make sure that lodash is included in your typings.json file

Update 1:

First, globally install typings by running

npm install typings -g

Then, use typings to install lodash with this command

typings install lodash --save

Finally, import the function you need from lodash like so:

import { add } from 'lodash';

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

Setting the sidebar width for Nebular with two sidebars in the layout: A step-by-step guide

Having two sidebars (identified as left and right) in my page layout, I initially set both sidebars to a width of 400px using the custom theme method with sidebar-width: 400px. However, I now need to change the width of the right sidebar to 700px. Is the ...

To validate any object, ensure that it contains a specific key before retrieving the corresponding value in typescript

When looking at a random object, my goal is to verify that it follows a certain structure. obj = {WHERE:{antherObject},OPTIONS{anotherObject}} Once I confirm the object has the key using hasProperty(key), how can I retrieve the value of the key? I thoug ...

Challenges in conducting asynchronous tests for Angular2 due to setTimeout complications

Using Angular2.0.1, I encountered an issue while trying to write unit tests for an angular component that involved async tasks. This is a common scenario and even the latest testing examples from Angular include async tests (see here). My test kept failin ...

The automatic inference of function argument types and the implementation of conditional types

I'm facing a specific scenario: There's a function that takes in a boolean and returns either a RealItem or an ImaginaryItem. I'm using conditional types to determine the return type based on the boolean argument. type RealItem = { color: s ...

What steps should I take to correct the scoring system for multi-answer questions in my Angular quiz application?

When answering multiple-choice questions, it is important to select ALL of the correct options in order to increase your score. Selecting just one correct answer and then marking another as incorrect will still result in a score increase of 1, which is not ...

The calculation of the deducted amount is inaccurate

I have two values, cost and quantity, in an array. Within this array, there is a button that, when clicked, will decrease the value of quantity by 1 unit. As a result, the cost should also decrease proportionately based on the cost of one unit in the quant ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

Managing state within SolidJS components using Immer's "produce" for nested state handling

I've been working on a SolidJS application where I store a large JSON object with nested objects. For undo and redo actions, I'm using Immer to generate patches. Although technically I'm storing a class with multiple layers of nesting, Immer ...

What is the best way to create a versatile svelte component that can be utilized across various projects?

Currently, I am in the process of developing two distinct web applications using svelte/typescript: Site A, which serves as the public-facing front end and must be optimized for speed and efficiency Site B, the administration UI where editors manage and u ...

Utilize the index of a for loop to manipulate an Angular string

When working with different objects and creating forms simultaneously, I've come across a challenge. My initial idea for handling the submission was to use the following code: <form (ngSubmit)="submitForm{{u}}()"> However, incorporating the in ...

Utilizing props in styled components with Emotion-js and Typescript is not feasible

Check out this simple React component I created: import React, { ReactChild, ElementType } from 'react' import styled from '@emotion/styled' type WrapperPropsType = { size?: SizeType } type ButtonPropsType = { as?: ElementType< ...

When RouteProps is used to initialize useState, the state is not set

I am facing a dilemma with a component that utilizes useState. The state is initially set using a property from RouteComponentProps. Strangely, it functions correctly when I manually type the URL in the browser's address bar, but not when the URL is c ...

In TypeScript, errors are not displayed in React Hooks when using the Pick type

Link to code sandbox demo import { useMemo, useState } from "react"; import "./styles.css"; export default function App() { type TTest = { t1: string; t2: string; }; // No issues with useState and useMemo declarations ...

Learn the process of setting up a connection between Express JS and the NotionAPI using both POST and

As someone who is new to backend development, I am currently working on integrating a simple Notion form into a Typescript website. To guide me through the process, I found a helpful tutorial at . The tutorial demonstrates how to send data from localhost:3 ...

Palantir Forge: Enhancing Column Values with Typescript Functions

I am seeking assistance with a TypeScript function related to ontology objects. I want to develop a TypeScript program that accepts a dataframe as input. The objective is to nullify the values in other columns when a value from a row in a particular column ...

Avoid using the Input formControlName in the Angular 6 form

Before submitting the form, I want to be able to retrieve the value of the input tag with formControlName. I have tried creating a method to accomplish this, but I am unable to access the current input value. When I removed the formControlName to exclude ...

What are the steps to enable readonly or disabled functionality in Ionic 2?

Trying to make a field readonly or disabled in an ionic2 form: <ion-item> <ion-label fixed>Category <ion-icon name="ios-arrow-forward"></ion-icon></ion-label> <ion-input type="text" [disabled]="false" id="category_ ...

One important rule to remember when using React Hooks is that they must be called consistently and in the correct order in each render of the component. It

Encountering an issue while trying to use the ternary operator to determine which React Hook to utilize. The error message states: "React Hook "useIsolationDynamicPhase" is called conditionally. React Hooks must be invoked in the same order during every co ...

Encountering the error message "React child is not valid as a Gatsby wrapRootElement" while using TypeScript with Gatsby

I've been exploring ways to implement a theme provider in Gatsby using the wrapRootElement browser API. However, I seem to have hit a roadblock as I keep encountering an error message that says "Objects are not valid as a React child (found: object wi ...

Display a loading spinner while the search bar makes an API request in Angular

I'm struggling with incorporating a loading spinner display when a user enters a search term in the search bar. When there is a change detected in the search term property, an API request is made to populate the lists in the view with the relevant dat ...