Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should scripts be put into angular.json or into index.html?

Tags:

angular

With Angular you have two options to load scripts (js and css):

  1. In the index.html: <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
  2. In the angular.json: "styles": ["node_modules/font-awesome/css/font-awesome.css"]

What's the advantage of each option? To my understanding, the things in angular.json are bundled together while the scripts linked in index.html are loaded dynamically. So it boils down to the discussion whether it's better to having prebundled scripts or loading them e.g. from a CDN? Or are there other benefits from putting scripts into angular.json e.g. of organizational nature? Is it "cleaner" for some reason?

like image 505
bersling Avatar asked Oct 16 '19 07:10

bersling


1 Answers

Basically this is designed intentionally by the Angular team. In short, yes you can use either and you won't see any difference for a simpler project. But there are few difference between both of them.

  • An array of style/script files to add to the global context of the project if you add it in angular.json file will also be included in the bundle while build, where as if you define file/CDN in index.html this will load separately.

  • As per my understanding, assets that load via index file will not get copied in the bundle, but rather, it will show in the network tab.

  • Assets defined via angular.json file will have more features, such as -

    1. glob: A node-glob using input as base directory.
    2. input: A path relative to the workspace root.
    3. output: A path relative to outDir (default is dist/project-name). Because of the security implications, the CLI never writes files outside of the project output path.
    4. ignore: A list of globs to exclude.

For example -

{ "glob": "**/*", "input": "src/assets/", "output": "/assets/" },

or

{ "input": "src/external-module/styles.scss", "inject": false, "bundleName": "external-module" }

For more information, I strongly recommend you to read this -

  • https://angular.io/guide/workspace-config
like image 54
Pardeep Jain Avatar answered Oct 04 '22 01:10

Pardeep Jain