George Edwards George Edwards - 28 days ago 31
TypeScript Question

Webpack2 equivalent of html script tags?

I have downloaded an npm module which recommends adding:

<link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" />
<script src="node_modules/ng2-toastr/bundles/ng2-toastr.min.js"></script>


To my index.html file.

Is there a way that I can require the same references with Webpack 2 from an angular2 component?

e.g.

import 'ng2-toastr.min.js'


in the component?

Answer

The advice given in the instructions is strange. You should not have to ever include the <script> tag, since you are using webpack, the script will load automatically for you as part of your webpack bundle.

As for the css, you can use webpack for that as well. First you will need to install the appropriate loaders to be able to load the css file and to apply the styles to the dom:

npm install --save style-loader raw-loader 

Then somewhere in your typescript files you can do:

import 'style!raw!../node_modules/ng2-toastr/ng2-toastr.css'

(note that the relative path to your ../node_modules might differ depending on the level of nesting in your application.

The style! and raw! prefixes are instructions for webpack to process the given script through "loaeers".

The raw loader will just read in the css file as is without trying to do any further processing (you can use the css! loader if you need to do additioanl things like @import from the .css file, but in this case that's not necessary, so the easiest is the raw loader.

The style loader takes the css loaded by the raw loader and programatically applies it to the current page dom. It does not actually create a <style> tag with a src="url....", but it achieves the important part which is to make sure the styles in the loaded css are loaded on the page.

If you need to do this often, you can always add the loader config to your webpack.config.js:

module: {
  loaders: [
     {test: /\.tsx?$/, loader: 'ts-loader'},
     {test: /\.css$/, loader:'style!raw'}
  ] 
}

Then you can just do:

import '../node_modules/ng2-toastr/ng2-toastr.css'
Comments