Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I configure grunt-usemin to work with relative path

I have a grunt project backed by a yeoman-generator that I've built based on the generator-webapp, if it's of any help, you can find it on GitHub

The grunt project makes us of the grunt-usemin task.

My project involve building a multilingual website, and to keep things clean, I've decided to put all the pages written in a language in a folder name after the 2-letter shortcode of the said language.

| project/
|--dist/
|----en/
|------index.html
|------404.html
|------...
|----fr/
|------index.html
|------404.html
|------...

The files are made from handlebars templates and processed with assemble. In the layout I have building blocks for usemin such as

<!-- build:css(.tmp) styles/main.css -->
<link rel="stylesheet" href="../styles/main.css">
<!-- endbuild -->
<!-- build:js scripts/vendor/modernizr.js -->
<script src="../bower_components/modernizr/modernizr.js"></script>
<!-- endbuild -->

Which, in a perfect world would translate to

<link rel="stylesheet" href="../styles/main.css">
<script src="../scripts/vendor/modernizr.js"></script>

but instead shows

<link rel="stylesheet" href="styles/main.css">
<script src="scripts/vendor/modernizr.js"></script>

which is less than ideal in my case. The relevant part of the Gruntfile.js looks like this

    useminPrepare: {
        options: {
            dest: '<%= yeoman.dist %>'
        },
        html: [
            '<%= yeoman.app %>/fr/{,*/}*.html',
            '<%= yeoman.app %>/en/{,*/}*.html'
        ]
    },
    usemin: {
        options: {
            dirs: ['<%= yeoman.dist %>']
        },
        html: [
            '<%= yeoman.dist %>/fr/{,*/}*.html',
            '<%= yeoman.dist %>/en/{,*/}*.html'
        ],
        css: ['<%= yeoman.dist %>/styles/{,*/}*.css']
    }

I have tried to use the basedir option by setting it to <%= yeoman.dist %> as well as changing the build blocks to

<!-- build:css(.tmp) ../styles/main.css -->
<link rel="stylesheet" href="../styles/main.css">
<!-- endbuild -->
<!-- build:js ../scripts/vendor/modernizr.js -->
<script src="../bower_components/modernizr/modernizr.js"></script>
<!-- endbuild -->

But unfortunately wasn't able to get a proper output.

More specifically, the first one didn't change anything, the second one had the folders scripts and styles outputted one level too high in the hierarchy

| project/
|--app/
|--dist/
|--styles/
|--scripts/

instead of

| project/
|--app/
|--dist/
|----styles/
|----scripts/

Would anyone happen to know what to do ? It seems a rather simple usecase but I couldn't find the help I need via Google, GitHub or SO...

like image 921
Jérémie Parker Avatar asked Sep 23 '13 17:09

Jérémie Parker


4 Answers

I believe that you can achieve what you need in this way:

Html file:

    <!-- build:css styles/main.css -->
    <link href='../styles/css/style.css' rel='stylesheet' type='text/css'>
    <link href='../styles/css/responsive.css' rel='stylesheet' type='text/css'>

    <link href="../styles/css/skins/welld.css" rel='stylesheet' type='text/css' id="skin-file">
    <!-- endbuild -->

Gruntfile.js

        useminPrepare: {
            options: {
                dest: '<%= yeoman.dist %>/'
            },
            html: ['<%= yeoman.app %>/snippets/head.html','<%= yeoman.app %>/snippets/tail.html']
        },
        usemin: {
            options: {
                dirs: ['<%= yeoman.dist %>/'],
                blockReplacements: {
                    css: function (block) {
                        return '<link rel="stylesheet" href="../' + block.dest + '"/>';
                    },
                    js: function (block) {
                        return '<script src="../' + block.dest + '"></script>';
                    }
                }
            },
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css']
        }

The key solution is in the blockReplacements option of the usemin task. Basically, the task will put your files under <%= yeoman.dist %>/styles/main.css, while your html will be under <%= yeoman.dist %>/en/somefileinEnglish.html and every instance of 'styles/main.css' in this file will be replaced with '../styles/main.css', adding the correct relative path.

As an extra tip, if you are building a multilingual website, you may want to consider grunt-i18n to translate your file while building, so you won't need to maintain a different html file for every language.

like image 182
Luca Camerini Avatar answered Oct 20 '22 22:10

Luca Camerini


I was building my own Grunt scaffolding and I was frustrated by this issue. I managed to create a work around that I'd like to share it with you.

I'd like to use an example of my own to illustrate the reason behind his issue and how I managed to work around. Say my directory structure is the following:

| in/
+---- pages/
|    +---- login.html
+---- js/
|    +---- s1.js
|    +---- s2.js
+---- index.html
| out/
| Gruntfile.js

Where in/ is where all of my source files reside and out/ is dest directory, where all of the output files will be stored. Say I want to import s1.js into login.html, I'd write something like this:

<!-- build:js ../js/login.js -->
<script src="../js/s1.js"></script>
<!-- endbuild -->

In here, usemin block performs a simple string replace so the output path should be exactly where I want to link the output file. The problem occurs when instead of having login.js land at out/js/login.js, useminPrepare end up landing it at js/login.js. The reason behind this is that useminPrepare simply performs a path join between dest (which is out) and the output path (which is ../js/login.js), while it should have performed a path join with respect to where the HTML file is found.

In order to work around this issue, observe that if I set dest to out/pages which respects where login.html is found, it will work out fine. BUT notice that if index.html imports js/s2.js in a similar fashion, then that will get screwed up. So in order to work around THAT, we need to create one useminPrepare target for index.html with dest: "out" and another target for login.html with dest: "out/pages". Hence my useminPrepare config now looks something like this:

"useminPrepare": {
    t1: {
        dest: "out",
        files: [{src: ["in/*.html"]}],
        ...
    },
    t2: {
        dest: "out/pages",
        files: [{src: ["in/pages/*.html"]],
        ....
    }
}

All targets will have to run. Now you will probably say; what if I have even more HTML files under other subdirectories? Does that mean I will have to create one target for each directory where HTML files are found? This is pain in the ass and stupid. It IS! I agree. So I wrote a very special grunt task to help out. I call it useminPreparePrepare I deliberately named it stupidly, because it IS stupid. I'm really hoping to get rid of this work around one day when usemin people fixes this issue. As its name suggests, useminPreparePrepare prepares configs for useminPrepare. Its own configs mirrors useminPrepare (in fact, most configs are simply copied over) with one exception; you will have to add a src property that points to the source root directory where all of your source files reside, so that it can figure out the relative path between your source root and HTML files. It will perform essentially what I mentioned above. Plus, it does the same for staging directory too, so staging files wont' break out of the staging directory. You can even have multiple targets in useminPreparePrepare, it will copy over the options for the target you ran.

In order to use this work around, you will first have to import useminPreparePrepare. I didn't put it on npm, so you will have to just copy and paste it. I don't mind. Then simply rename your useminPrepare config to useminPreparePrepare, and add src property. For the above example, src: "in". Then you need to run useminPreparePrepare with whichever target you'd normally like, then immediately run useminPrepare without specifying target so that all targets will run. Given the above example Grunt config could look something like this:

"useminPreparePrepare": {
    html: "in/**/*.html",   // All HTML files under in/ and its subdirectories.
    options: {
        src: "in",
        dest: "out",
        ....
    }
},
"copy": {
    html: { // Copies all HTML files from in/ to out/ preserving their relative paths.
        files: [{
                expand: true,
                cwd: "in",
                src: ["**/*.html"],
                dest: "out"
            }
        ]
    }
},
"usemin": {
    html: "out/**/*.html",  // Process all HTML files under out/ and its subdirectories.
    ...
}

You can see that the above config is simple enough to include all HTML files recursively under the source directory. useminPreparePrepare takes care of all the stupid work arounds while looking just like useminPrepare.

I hope this helps!

like image 39
initialxy Avatar answered Oct 20 '22 21:10

initialxy


My solution was to manually modify grunt-usemin plugin.

Open node_modules/grunt-usemin/fileprocessor.js in you favourite text editor. Somewhere around line 152 find:

if (assetSearchPath && assetSearchPath.length !== 0) {
  this.file.searchPath = assetSearchPath;
}

and replace it with:

if (assetSearchPath && assetSearchPath.length !== 0) {
  this.file.searchPath.splice(0, 0, assetSearchPath);
}

By default this.file.searchPath is an array containing the absolute path to the current file. There's no point in overwriting it with ['dist'], it's better to prepend the array with 'dist'. This way if an item is not found in 'dist' directory it might be concluded that either the path is relative or it's wrong. Thus we use the second value from the searchPath array to look for the file and if it was a relative path - we get what we wanted.

like image 1
Michał Miszczyszyn Avatar answered Oct 20 '22 22:10

Michał Miszczyszyn


I used multiple targets as shown below:

 useminPrepare: {
        target1 : {
                src : ['target1/*.html'],
                options : {
                    dest: 'out'
                }
            },

            target2 : {
                src : ['target2/folder/*.html'],
                options : {
                    dest: 'out/subfolder'
                }
            }
    },

Then in the HTML block you could this:

<!-- build:js ../subfolder/script.js -->
<script src="../subfolder/scripts/main.js></script>
<!-- endbuild -->
like image 1
franksprings Avatar answered Oct 20 '22 22:10

franksprings