0

I need to import jQuery in my Angular 7 application and I noticed that where are two ways to do this.

  1. Importing the jquery.min.js file into the scripts property of angular.json
  2. Importing jQuery from ts code (for example in main.ts or a module) using import 'jquery';

What is the difference between these approaches?

2 Answers 2

2
  1. Makes the script global (like placing a script tag in index.html)

  2. Makes use of modules, which avoids global scope pollution, and lets tools like Webpack optimise the bundling process, e.g. by “tree-shaking”.

Sign up to request clarification or add additional context in comments.

Comments

2

First I must say that mixing JQuery with angular is in most cases a bad idea, So I hope You have a good reason for it. About your question

When importing a file using scripts property of angular.json, You do exactly that - importing the entire file and running it's code. On angular, the will be done prior to the execution of your angular app code.

On the other hand, when importing a module (after installing it using a package manager like npm), You can import only the modules you need, which usually means less code in being executed by the browser. I wrote usually, because when using JQuery you most likely import the entire library in anyway.

I would always prefer installing using a package manager when possible, since:

  • It is easier to install and update
  • It is a standard when using frameworks like angular
  • It allow to import only the actual code I need rather the entire library (Which doesn't matter much in the case on JQuery, but really useful for other libraries).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.