简体   繁体   中英

How to change html (jade template) to use *.min js and css in production?

I'm using Grunt to compile jade templates to html, uglify/concat js and minimize/concat css.

During development I use the combination of connect and watch to serve my front-end and pick up changes automatically. In this I also use the 'source' js and css (and not the uglified/concatted/minified version).

Now when I generate the production html, js and css I wonder what the best solution is to change the inclusions of the *.min js and css.

To be more specific in my html I eg include: a.css b.css c.css a.js b.js

for development this is fine, but when generating the production version I want:

common-min.css common-min.js

Of course I don't want to change the Jade templates manually so I'm looking for a better approach, probably with the use of some Grunt plugin.

You can pass data into your template that indicates what environment you are in, and then switch what you're including based on that.

// In your route:
res.render("index", { env: "development" }); // maybe use NODE_ENV in here?

// Then in your jade template:
head
  if env == 'development'
    link(href="a.css", rel="stylesheet", type="text/css")
    link(href="b.css", rel="stylesheet", type="text/css")
  else
    link(href="min.css", rel="stylesheet", type="text/css")

See the Jade docs, and search for "conditionals": http://jade-lang.com/reference

@Marcel

What you're looking for is a jade build block processor (or more commonly an HTML build block processor). Unfortunately, for jade there only appears to be a gulp plugin, and not one for grunt.

https://www.npmjs.com/package/gulp-processjade

This example may suit your needs.

// build:js app.min.js
script(src='app.js')
// /build

@Jakerella

For each version, a production build is typically run once. So it's more effective to use a build server, task manager, or dependency manager; and less effective to dynamically generate the production version of the HTML page within the server's request handler. Don't use env with res.render() - logic used to build a page for production isn't needed when the entire server is built for production. This production logic also makes the request handler less modular, because it's coupled to the HTML page. Only build servers (ones dedicated to builds) should incorporate build logic. And, while the dynamically generated pages can be cached to avoid the repeated computation in rendering the production version of the HTML page, that's memory overhead that could be avoided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM