87

I am not sure how to include JS files (vendors) after switching Angular Cli from SystemJs to Webpack.

For example

Option A

I have some js files that were installed via npm. Adding script tags to the head tag like this does not work. Nor does it seem like the best way.

<head>
   <script src="node_modules/some_package/somejs.js">
</head>

//With systemJs I could do this

<head>
   <script src="vendor/some_package/somejs.js">
</head>

Option B

Include these js files as part of the webpack bundle. This seems like the way it probably should be done. However I am not sure how to do this as all of the webpack code seems to be hidden behind the angular-cli-webpack node package. I was thinking maybe there is another webpack config that we might have access to. But I am not sure as I didn't see one when creating a new angular-cli-webpack project.

More Info:

The js files I am trying to include need to be included before the Angular project. For example jQuery and a third party js lib that isn't really setup for module loading or typescript.

References https://github.com/angular/angular-cli/blob/master/WEBPACK_UPDATE.md https://github.com/angular/angular-cli/tree/webpack

4
  • Seems they switched to typescript 2.0 Commented Aug 9, 2016 at 16:25
  • Take a look at blogs.msdn.microsoft.com/typescript/2016/06/15/… Commented Aug 9, 2016 at 16:25
  • Thanks for the link, but that isn't what I am looking for. That is for adding the definition files. I am trying to figure out what is the proper way to include thirdparty JavaScript libraries into my project. Commented Aug 9, 2016 at 16:30
  • Webpack angular2 example how to bundle different one for vendor one for polymorphism one for the app and one for the css to keep clean app. Commented Aug 9, 2016 at 17:30

5 Answers 5

97

Last tested using angular-cli 11.x.x with Angular 11.x.x

This can be accomplished using scripts:[] in angular.json.

{
  "project": {
    "version": "1.0.0",
    "name": "my-project"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": ["assets"],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "app",
      "mobile": false,
      "styles": [
        "styles.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.js"
      ],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "addons": [],
  "packages": [],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "prefixInterfaces": false
  }
}

Note: As the documentation suggests in the global library installation: if you change the value of your styles (or scripts!) property, then:

Restart ng serve if you're running it,

..to see the scripts executed in a **globalcontext via the scripts.bundle.js file.

Note: As discussed in the comments below. JS libs that support UMD modules via es6 imports such as jQuery can also be imported into your typescript files using the es6 import syntax. For example: import $ from 'jquery';.

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

13 Comments

How can I reference jquery in Typescript once I have added the script to angular-cli.json?
BTW If the external file being added is a polyfill, then there is a dedicated mechanism for that nicely described in src/polyfills.ts (as of beta.31)
If you're using jQuery in your Angular project, then you're doing it wrong. I love jQuery, it took me far on my career, but if you're using Angular correctly, there is no more need for jQuery.
@BlairConnolly, While I agree and we would love to get rid of jQuery. We are consuming a Jquery UI from another team within our company whom doesn't have time to rewrite the whole UI at the moment. So sometimes people just don't have a choice.
@KrisHollenbeck I'm not trying to be a jerk but seriously consider the complexity of the tools we have accreted in order to adopt ES Modules. From transpilers, to frameworks, to loaders, to package managers, to bundlers, to CLIs we use incredibly complex, interdependent and often incompatible tools to leverage modules. We should be loath to do so if we throw away all the benefits. This should be a last resort approach, but will become de facto for users who don't understand why the complexity is even there, just accepting it.
|
25

There is a subtle difference to using scripts:[] then to adding something to the <head> with <script>. Scripts from scripts:[] get added to the scripts.bundle.js that gets always loaded in the body tag and will thus be loaded AFTER scripts in <head>. Thus if script loading order matters (i.e. you need to load a global polyfill), then your only option is to manually copy scripts to a folder (e.g. with a npm script) and add this folder as an asset to .angular-cli.json.

So if you really depend on something being loaded before angular itself (Option A), then you need to copy it manually to a folder that will be included in the angular build and then you can load it manually with a <script> in <head>.

Thus, for achieving option a you have to:

  • create a vendor folder in src/
  • add this folder as an asset to .angular-cli.json:
"assets": [
    "assets",
    "favicon.ico",
     "vendor"
  ]
  • copy your vendor script node_modules/some_package/somejs.js to vendor

  • load it manually in index.html: <head> <script src="vendor/some_package/somejs.js"> </head>

However most of the time you only need this approach for packages, that need to be available globally, before everything else (i.e. certain polyfills). Kris' answer holds true for Option B and you get the benefit of the webpack build (Minification, Hashes, ...).

However if your scripts need not be globally available and if they are module-ready you can import them in src/polyfills.ts or even better import them only when you need them in your specific components.

Making scripts globally available via scripts:[] or via manually loading them brings it own set of problems and should really only be used, when it is absolutely necessary.

6 Comments

This is great because I can create a js config files per environment leave them there and load them at runtime instead of using environment.ts files and having to build angular for each environment (terrible...)
Do you have any example to use polyfills or load in specific components?
@SteveLam Please be more specific or ask a new question. Usually polyfills would not be loaded in a specific component, but globally unless you want you components to be self-contained but even then it is prefered to define the runtime environment that you expect and let the consumer of the component decide when and how to load a polyfill.
Thank Chris, do you have any article about that?
Hi im using angular 7, when i run mi app the script is loaded in the index page but i need use the script in other page, when i click in other page the script is unloaded, how can i load it on a specific page or for a whole application?
|
4

You need to open file .angular-cli.json file and need to search for "scripts:" or if you want to add external css you need to find the word "styles": in the same file.

as an example shown below you will see how the bootstrap Js(bootstrap.min.js) and bootstrap CSS(bootstrap.min.css) includes in .angular-cli.json:

"styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],

For sure if you have your own js file you can add your file path here in .angular-cli.json at the same place(in "scripts":[]).

Comments

3

You might want to have a look at this page: https://github.com/angular/angular-cli#global-library-installation

It show the basics of how to include .js and .css files

Some javascript libraries need to be added to the global scope, and loaded as if they were in a script tag. We can do this using the apps[0].scripts and apps[0].styles properties of angular-cli.json.

1 Comment

Link only answers are discouraged. Please quote the essential parts of the answer from the reference link(s), as the answer can become invalid if the linked page(s) change.
-1

I havn't used angular-cli before but I'm currently working with an Angular/Webpack build. In order to provide my application with jQuery and other vendors I use webpack's plugin, ProvidePlugin(). This will typically sit in your webpack.config.js: Here's an example for jquery, lodash and moment libraries. Here's a link to the documentation (which is vague at best)

plugins: [
  new webpack.ProvidePlugin({
    $: 'jquery',
    _: 'lodash',
    moment: 'moment',
  })
]

Incredibly, it actually allows you to use it right away, providing all other webpack setup has been done correctly and have been installed with npm.

2 Comments

The angular cli webpack config is actually part of the angular cli node package. So unfortunately I can not modify that. For example in the CLI there are preset commands to build. ng build this is all handled by the cli. But I was thinking there is probably a way to add things as part of the build. But I haven't seen any clear example.
Ah my apologies. I'd filtered angular 2 questions but this one slipped through. Best of luck.

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.