user3471528
user3471528

Reputation: 3053

Differences between importing libs in angular.json and component

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?

Upvotes: 0

Views: 440

Answers (2)

yuval.bl
yuval.bl

Reputation: 5074

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).

Upvotes: 2

user11390576
user11390576

Reputation:

  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”.

Upvotes: 2

Related Questions