Integrating jquery into an angular project

I am facing an issue setting up jquery in an angular 6 project. When I try to import it in the ts file, I encounter the following error:

Error: This module can only be referenced with ECMAScript imports/exports by turning on the 'allowSyntheticDefaultImports' flag and referencing its default export

The runtime error is:

Module '"/types/jquery"' resolves to a non-module entity and cannot be imported using this construct.

Here is my TypeScript code:

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
@Component({
  selector: 'app-anim',
  templateUrl: './anim.component.html',
  styleUrls: ['./anim.component.css']
})


export class AnimComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    $(function() {
      $('.intro').addClass('go');

      $('.reload').click(function() {
        $('.intro').removeClass('go').delay(200).queue(function(next) {
          $('.intro').addClass('go');
          next();
        });

      });
  });

  }

}

I have also added allowdefault imports to my tsconfig.json as suggested by others. Here is my tsconfig:

{
  "compileOnSave": false,
  "compilerOptions": {
    "paths": { "*": ["types/*"] },
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "allowSyntheticDefaultImports": true,
    "typeRoots": [
      "node_modules/@types"
    ],

Angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "textAnimation": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/textAnimation",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": ["./node_modules/jquery/dist/jquery.min.js"],
            "es5BrowserSupport": true
          },

I am struggling to understand what else I need to do to get jquery to work. Any help would be greatly appreciated. Thank you in advance.

Answer №1

To begin, you must first download and install the following two packages:

npm install jquery --save
npm install @types/jquery --save

Next, you will need to add the path for the jQuery library in the scripts section of the architect => build within the angular.json file:

"scripts": [
  "node_modules/jquery/dist/jquery.min.js"
]

Finally, include jQuery in the types section of tsconfig.app.json. If desired, you can modify another tsconfig file within the angular.json file (architect => build => tsConfig section):

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["jquery"]
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}

This will allow you to avoid having to declare jQuery in every component like so:

declare var $: any;

Answer №2

By including jquery in the scripts section of your angular.json file, you have already imported it. This means you can now utilize jquery simply by declaring a variable.

import { Component, OnInit } from '@angular/core';
declare var $: any;
...

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

The element "center" is not a recognized HTML tag in Angular 4

The center tag is not functioning and it says that center is an unknown element. <center> <a><img class="placeholder_img" src="img/placeholder.png"></a> </center> When I used the above HTML tags, it stated that "center i ...

Incorrect order in Angular2 NgFor within tree model when elements are removed and then added back

Currently experimenting with Angular 2 alpha version 44. Working with a tree model that utilizes recursion for display purposes. Each group contains 'Criterions', 'Segments', and other 'Groups'. Elements can be added or delet ...

Testing the visibility of an element in Jasmine after it has been clicked

Just starting with Jasmine, I have an elegant dropdown that shows up when a button is clicked. I am interested in verifying that the dropdown menu does indeed become visible upon clicking the button. describe("showing visible dropdown", function () { ...

Users can still check disabled checkboxes within the Mat table

I'm encountering an issue with a Mat table that has a checkbox column. Even though I've disabled certain checkboxes based on specific conditions, users are still able to select the checkbox by clicking on the row. How can I prevent this behavior ...

What is the solution to prevent the div tag from being empty within Jquery UI Tabs?

I found this example that I am currently following: http://jqueryui.com/demos/tabs/#ajax After clicking on Tab1 and Tab2 in their example, the text disappears immediately, and the div box shrinks before new data is loaded. Is there a better way to handle ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

Creating a dynamic text field integrated with Google Places in Ionic 4: a step-by-step guide

I am currently implementing the google-place-api autoComplete feature in my project, but I encountered an error: TypeError: Cannot read property 'getInputElement' of undefined .html <section [formGroupName]="i" *ngFor="l ...

There are times when the `window.location.replace` function does not

I have implemented a Bootstrap Dropdown feature that allows users to select a language for site translation, append the URL with the selected language, and then reload the page. Initially, it works well for the first set of translations like en|es. Howeve ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

Hold off on proceeding until the subscription loop has finished

Is there a way to verify that all results have been successfully pushed to nodesToExpand after running the for loop? The getFilterResult function is being called via an HTTP request in the nodeService service. for(var step in paths) { this.nodeSe ...

Javascript - Unable to update button text

I am encountering a problem with updating the text of a Bootstrap button when a collapsed element is opened or closed. The icon part is updating successfully, but I am struggling to get the button text to update and I cannot figure out why. My knowledge o ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

What is the best way to align these div elements within a table cell?

I am encountering an issue with the placement of elements. What I am striving for is something like this: https://i.stack.imgur.com/VSFXE.png where a div with several other divs inside is positioned at the top of the td, and another div is at the bottom o ...

implement a click event handler for GLmol (webGL)

Check out GLmol, a Molecular Viewer built on WebGL and Javascript by visiting You can see a demo of GLmol in action at I am interested in adding a click function to GLmol. For example, when I click on a ball, I would like to retrieve information about it ...

Manipulating, modifying, and verifying distinct information rather than inputting to / retrieving from the model through the use of Reactive Forms

My configuration I am retrieving a value from the database as a number. This value must always be a number, except when displaying it in an input element and validating user input. In those cases, the number needs to be a HEX value. Here is the desired p ...

What is the best way to transfer the value of one directive attribute to another directive in AngularJS?

For instance: <custom-main> <custom-sub1 att-name="test"></custom-sub1> <custom-sub2></custom-sub2> </custom-main> JavaScript Source Code bosAppModule.directive('custom-main',[&apos ...

``Only Firefox supports jQuery animations, all other browsers fail to render them properly

This particular issue is a bit complex to articulate, so I'll begin by providing the code and then proceed to elaborate on the problem as best as I can. I'm assuming that you've already compared the results in Firefox and other browsers. He ...

Converting JSON data into TypeScript interface objects within an Angular 2 environment

I have a JSON dataset with the following structure: { "timestamp": 1467471622, "base": "USD", "rates": { "AED": 3.673027, "AFN": 68.475, "ALL": 123.095199, "AMD": 476.8075, "ANG": 1.78385, "AOA": 165.846832, "ARS": 15.05 ...

Navigating away from an Ionic 2 app running in the browser and then returning: tips and tricks

Currently, I am setting up my oauth2 authentication in Ionic2. Through my research, I have discovered that the Cordova InAppBrowser plugin can be utilized to handle the process of navigating to the website and granting access to the App. However, I am st ...

Jasmine: utilizing unit test to spy on the invocation of a nested function

When running unit tests for an Angular app, I need to spy on a function called func1 to check if it is being called. However, within func1 there is a call to func2 and I also want to spy on that to see if it is being called. How should I structure my unit ...