using npm scripts to Inject *.js and *.css into index.html
Asked Answered
F

2

8

I´m looking into switch from gulp/grunt to only use npm scripts. But I cant really solve how to get *.js and *.css from a given path and add it to the index.html file.

must I add it thru a "index.js" file or can I do something like...

"scripts": {
 "inject": "inject src/app/*.js",
},

and then it will add it in my index.html where I have specified it like...

/* inject:js */
Factoring answered 21/2, 2016 at 21:43 Comment(4)
Is there really no one with an answer to this? :/Factoring
This looks promising npmjs.com/package/postbuildRoster
Indeed!.. will take a look at it!Factoring
I used it over the weekend in a project and it worked well. Keep in mind This module was written in ES6 and requires node >= 4.0.0.Roster
F
4

The suggestion by Chris Traveis worked out pretty nice. So the answer to my problem was solved using https://www.npmjs.com/package/postbuild

Factoring answered 23/5, 2016 at 7:44 Comment(1)
npmjs.com/package/htmlparser2 parser is a powerful alternative that will allow any tag to be injected(instead of only JS and CSS).Redbreast
O
1

There were no answers in the last 3 months on this popular topic, probably because there are wrong assumptions in the question. Distilling your question,

...how to get *.js and *.css from a given path and add it to the index.html file

To be short, do it manually. Use a good npm boilerplate such as npm-build-boilerplate and add the compiled JS and CSS files manually into your HTML.

... must I add it thru a "index.js" file, or <2nd option>

No. Add the files manually. Let me elaborate more.

With npm scripts you construct a pipeline and you know where your uglified JS files and compiled SCSS files are rendered. Yes, I have "main": "index.js", row in my package.json, but there's no "index.js" in my project at all. I get npm scripts to crunch files in various folders, to output them into other folders and I manually add end CSS and JS files into HTML templates (in my case, static Hugo website's templates).

I see one case where "dynamism" in the HTML is needed — when you want to bust cache and add the unique strings to the end-point CSS/JS file names. However, then you might want to consider scripts that count MD5 hash of the files' contents, because if you run the build multiple times and your existing CSS or JS files haven't changed, you want to keep the old file names. Visitors might have cached them (and think about CDN too). In this sense, npm postbuild script mentioned in the comments above is inferior because it just uses "version" counter. Look for alternatives to npm postbuild to bust caches.

Oblate answered 21/5, 2016 at 19:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.