Dynamic path in Yeoman build comment tag

2019-06-14 02:48发布

问题:

Is there a way to get dynamic path into the Yeoman build tag, e.g. for

<!-- build:js scripts/modernizr.js -->

The use-case would be to push in a different path in the layout for differently nested pages, either / to webroot or ../../ to an upper level, e.g. something like

<!-- build:js <%= config.path.script %>/modernizr.js -->

Related topic has already been discussed in a question of Yeoman/Grunt usemin subfolders, but what about a more graceful/flexible solution? Ideas?

回答1:

If you compile to static HTML, you can have a look at my grunt-magic-paths task. It can take a user defined needle (default is path:) and automatically resolve the path to a file based on its name alone. So you could do this:

<script src="path:modernizr.js"></script>

And based on the output directory it will resolve the path names automatically. The one caveat is that a linked path must be a unique one; i.e. you can't link two different copies (versions) of Modernizr with the same filename.

You may find though that for larger applications having a build step like this is brittle, especially as your application grows and the number of paths increase. I'd strongly recommend the use of absolute paths for anything larger than a personal portfolio; you can then keep the domain path in a config file (in JS, something like this):

module.exports = 'http://mydomain.com';

Then for use in production:

var domain = require('config.js');
console.log(domain);
// => http://mydomain.com

Change the config.js file depending on your environment; you may want to .gitignore it, and provide a sample config with dummy data instead. Because Grunt runs on top of Node you then have this config in your build step as well as your application (again I'm assuming you're writing a Node application, for other projects you may prefer JSON or PHP config files).