Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"usemin:css" doesn't generate correct image paths for relative urls #824

Closed
taktran opened this issue Jan 7, 2013 · 58 comments
Closed

"usemin:css" doesn't generate correct image paths for relative urls #824

taktran opened this issue Jan 7, 2013 · 58 comments

Comments

@taktran
Copy link

taktran commented Jan 7, 2013

I've generated a project using yeoman, and I have the following scss file which references an image using relative paths:

.compare {
  background-image: url("../img/insulin-v2.jpg");
}

However, it does not get properly converted to the correct ../img/[random-hash].insulin-v2.jpg format.

If I change it to an absolute path, it does convert it correctly, ie,

.compare {
  background-image: url("/img/insulin-v2.jpg");
}

...generates this in the yeoman build output

Running "usemin:css" (usemin) task

usemin:css - styles/4dcce6a3.styles.css
>> img/insulin-v2.jpg
was url("/img/insulin-v2.jpg")
now url("/img/46ee3ef4.insulin-v2.jpg")

(the previous relative url version doesn't produce any output after Running "usemin:css" (usemin) task)

I can't use absolute paths because I need to host somewhere where it is not the root directory. Any ideas?


My folder structure is

./app:
    index.html
./app/img
    insulin-v2.jpg
./app/sass:
    _grid.scss
    _normalize.scss 
    styles.scss

Gruntfile.js build settings are

// Build configuration
// -------------------

// the staging directory used during the process
staging: 'temp',
// final build output
output: 'dist',

mkdirs: {
  staging: 'app/'
},

// Below, all paths are relative to the staging directory, which is a copy
// of the app/ directory. Any .gitignore, .ignore and .buildignore file
// that might appear in the app/ tree are used to ignore these values
// during the copy process.

// concat style/**/*.css files, inline @import, output a single minified css
css: {
  'styles/styles.css': ['styles/**/*.css']
},

// renames JS/CSS to prepend a hash of their contents for easier
// versioning
rev: {
  js: 'scripts/**/*.js',
  css: 'styles/**/*.css',
  img: 'img/**'
},

// usemin handler should point to the file containing
// the usemin blocks to be parsed
'usemin-handler': {
  html: 'index.html'
},

// update references in HTML/CSS to revved files
usemin: {
  html: ['**/*.html'],
  css: ['**/*.css']
},

// HTML minification
html: {
  files: ['**/*.html']
},

// Optimizes JPGs and PNGs (with jpegtran & optipng)
img: {
  dist: '<config:rev.img>'
},

// rjs configuration. You don't necessarily need to specify the typical
// `path` configuration, the rjs task will parse these values from your
// main module, using http://requirejs.org/docs/optimization.html#mainConfigFile
//
// name / out / mainConfig file should be used. You can let it blank if
// you're using usemin-handler to parse rjs config from markup (default
// setup)
rjs: {
  // no minification, is done by the min task
  optimize: 'none',
  baseUrl: './scripts',
  wrap: true,
  name: 'main'
}

This could be related to #419, but I tried the .compass.rb file addition and the relative_assets: true, but they both didn't work.

@taktran
Copy link
Author

taktran commented Jan 7, 2013

Also maybe worth noting is that the rev:img task generates the correct hashed file with the relative or absolute urls ie, the output of build gives

Running "rev:img" (rev) task
img/insulin-v2.jpg >> 46ee3ef4.insulin-v2.jpg

@sleeper
Copy link
Contributor

sleeper commented Jan 7, 2013

Mainly:

  1. We're moving usemin out of yeoman base in yeoman/grunt-contrib, and this case must be treated
  2. This specific issue has also been treated in usemin at a commit which is not part of 0.9.6 (i.e. 0.9.6 is "only" 0.9.5 plus 1 commit)

@taktran
Copy link
Author

taktran commented Jan 7, 2013

So anything I can do right now to fix the issue? Should I use the master branch of yeoman or something?

@sleeper
Copy link
Contributor

sleeper commented Jan 7, 2013

No, the master branch of usemin is currently not working.
I would say that you can try using the commit 50dd2ba.

To do this you'll have to clone yeoman, checkout this particular commit, and change the version of yeoman in cli/package.json to something higher than 0.9.6 (to avoid updater kicking in ;))

@taktran
Copy link
Author

taktran commented Jan 7, 2013

Great, thanks!

I've branched it at https://github.com/taktran/yeoman/tree/usemin-patch.

Couldn't figure out how to npm install from a particular branch on github, but downloading it and installing from the cli folder worked.

@hemanth hemanth closed this as completed Jan 8, 2013
@emrecamasuvi
Copy link

Thanks you guys!
I came here from this stackoverflow article
For newcomers to solve the issue, follow these steps:

sudo npm uninstall yeoman -g
git clone git://github.com/taktran/yeoman.git
cd yeoman/cli
sudo npm install -g
sudo npm link

@ringvold
Copy link

When will this be fixed in yeoman? It seems like something people need to have fixed.

@emrecamasuvi
Copy link

@haraldringvold i guess they will fix this in yeoman 1.0, not sure though.

@sleeper
Copy link
Contributor

sleeper commented Feb 21, 2013

Should be fixed by yeoman/grunt-usemin

@olimungo
Copy link

I had the same issue (with yeoman1.0.0-beta.4 and grunt 0.4.1) and solved it by adding basedir in the options of my Gruntfile.js

    usemin: {
        html: ['<%= yeoman.dist %>/{,*/}*.html'],
        css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
        options: {
            dirs: ['<%= yeoman.dist %>'],
            basedir: ['<%= yeoman.dist %>']
        }
    },

@ghost
Copy link

ghost commented May 17, 2013

I had the same issue and I solved it like @olimungo but url image in css is not correct :(

@olimungo
Copy link

@dondinh : I've got something like this in my CSS:

background-image: url(../images/ui/logo_40.png);

It gets converted like this :

background-image:url(../images/ui/47378ff3.logo_40.png)

And I can find the following file in the "images" folder :

47378ff3.logo_40.png

@ghost
Copy link

ghost commented Jun 6, 2013

@olimungo : My issue is solved successful. Thank you very much

@josephspens
Copy link

I attempted @olimungo's solution above:

usemin: {
        html: ['<%= yeoman.dist %>/{,*/}*.html'],
        css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
        options: {
            dirs: ['<%= yeoman.dist %>'],
            basedir: ['<%= yeoman.dist %>']
        }
    },

And received the following error:

$ grunt usemin:html --stack
Running "usemin:html" (usemin) task

Processing as HTML - dist/404.html
Warning: Arguments to path.resolve must be strings Use --force to continue.
TypeError: Arguments to path.resolve must be strings
    at Object.exports.resolve (path.js:313:15)
    at Object.exports.relative (path.js:371:18)
    at new module.exports (/Users/joseph/Development/josephspens.github.io/node_modules/grunt-usemin/lib/htmlprocessor.js:148:27)
    at /Users/joseph/Development/josephspens.github.io/node_modules/grunt-usemin/tasks/usemin.js:102:20
    at Array.forEach (native)
    at /Users/joseph/Development/josephspens.github.io/node_modules/grunt-usemin/tasks/usemin.js:87:34
    at Array.forEach (native)
    at Object.<anonymous> (/Users/joseph/Development/josephspens.github.io/node_modules/grunt-usemin/tasks/usemin.js:84:16)
    at Object.<anonymous> (/Users/joseph/Development/josephspens.github.io/node_modules/grunt/lib/grunt/task.js:258:15)
    at Object.thisTask.fn (/Users/joseph/Development/josephspens.github.io/node_modules/grunt/lib/grunt/task.js:78:16)

Aborted due to warnings.

Elapsed time
usemin:html  538ms
Total        538ms

After doing some research, this results from an issue with path.join(), and everyone's suggestion ends up resulting in reinstalling node and grunt and making sure everything is updated and pointing to the right location. I did all that without success. It turns out the solution is much simpler, remove the baseDir string from the array:

usemin: {
        html: ['<%= yeoman.dist %>/{,*/}*.html'],
        css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
        options: {
            dirs: ['<%= yeoman.dist %>'],
            basedir: '<%= yeoman.dist %>'
        }
    },

According to the usemin docs, baseDir is supposed to be a string anyways.

@gsklee
Copy link

gsklee commented Nov 20, 2013

I'm using v0.4.3 of generator-webapp and still experiencing the same issue. The default template is using relative paths everywhere and seems to suggest a convention but it leads to this buggy behavior quickly.

Judging from the discussions above - is this an issue related with usemin?

@marcalj
Copy link

marcalj commented Nov 23, 2013

For anyone having troubles with this again, like me, I solved the issue appending "/images" path to assetsDir config:

usemin: {
  html: ['<%= yeoman.dist %>/{,*/}*.html'],
  css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
  options: {
    assetsDirs: ['<%= yeoman.dist %>', '<%= yeoman.dist %>/images']
  }
},

@joemcgill
Copy link

Thanks @marcalj,

Was having this issue tonight and adding the /images folder to the assetsDir config worked perfectly.

@FrankFang
Copy link

Thanks @josephspens ! It works!

@FrankFang
Copy link

Thanks for @marcalj too !

@marcalj
Copy link

marcalj commented Dec 2, 2013

For files inside JS you have to use manual replacement right now (issue opened):

    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      js: '<%= yeoman.dist %>/scripts/*.js',
      options: {
        assetsDirs: ['<%= yeoman.dist %>', '<%= yeoman.dist %>/images'],
        patterns: {
          js: [[/(EuropeanUnion-24\.png)/, 'Replacing reference to EuropeanUnion-24.png']] // FIXME While usemin won't have full support for revved files we have to put all references manually here
        }
      }
    },

@marcalj
Copy link

marcalj commented Dec 2, 2013

You're are welcome :)

@gsklee
Copy link

gsklee commented Dec 6, 2013

Cool @marcalj! About the "files inside JS" issue - is it a usemin bug? What's the issue number?

@marcalj
Copy link

marcalj commented Dec 7, 2013

@gsklee Here: yeoman/grunt-usemin#235

Make sure to use multiple regex to catch repeated filenames: yeoman/grunt-usemin#244 (comment)

@gsklee
Copy link

gsklee commented Dec 8, 2013

Cool, thanks @marcalj!

@mkavrukova
Copy link

Thanks @marcalj

@npatten
Copy link

npatten commented Dec 23, 2013

Thanks @marcalj, that worked like a charm!

@uogood
Copy link

uogood commented Dec 26, 2013

Thanks @marcalj!

@marcalj
Copy link

marcalj commented Feb 26, 2014

@tastycode Hey, thanks for your research. I use the copy task for this problem for FontAwesome, not sure which is the best solution.

NOTE: This goes to copy.dist.files array.

{
            expand: true,
            cwd: '<%= yeoman.app %>/bower_components/ionicons/fonts/',
            src: ['**'],
            dest: '<%= yeoman.dist %>/fonts/' // Ionicons copy hack
        }

With this approach you don't get font revved and minified, what about with your solution?

Thanks!

@tastycode
Copy link

My solution gets revved (not sure if minified).. Honestly, if you solution works. I would rather just use it, i had to make so many changes everywhere to get mine to work. I don't need revving on these fonts.

@davepoon
Copy link

Use the copy task to copy the fonts, and remove or comment out the line of code for font renaming in rev task, this should fix the font not found issue.

rev: {
            dist: {
                files: {
                    src: [
                        '<%= yeoman.dist %>/scripts/{,*/}*.js',
                        '<%= yeoman.dist %>/styles/{,*/}*.css',
                        '<%= yeoman.dist %>/images/{,*/}*.{gif,jpeg,jpg,png,webp}'
                       //'<%= yeoman.dist %>/styles/fonts/{,*/}*.*'
                    ]
                }
            }
        },
copy: {
    dist: {
        files: [{
            expand: true,
            dot: true,
            cwd: '<%= yeoman.app %>',
            dest: '<%= yeoman.dist %>',
            src: [
                '*.{ico,png,txt}',
                '.htaccess',
                'images/{,*/}*.webp',
                '{,*/}*.html',
                'styles/fonts/{,*/}*.*'
            ]
        }

@derekdata
Copy link

Thanks @marcalj !

@xipengyang
Copy link

Thanks @marcalj!

@elegantcoder
Copy link

Thanks @marcalj !

@iheanyi
Copy link

iheanyi commented Jun 6, 2014

Another fix that I encounter was that I was getting messed up by relative paths within my URL link ('../../images'). If you have it in the format in parentheses, change it to ('/images') and that should fix a lot of issues.

@Munter
Copy link

Munter commented Jun 6, 2014

@iheanyi I would call that a bug. It's well defined that urls can relative from the CSS that include them. There is no excuse not to support that

@gintsgints
Copy link

Please fix this.

@alexanderjohn
Copy link

This is still an issue using yoeman 4.4, grunt contrib usemin 2.3 and the angular generator

@Gamatora
Copy link

Gamatora commented Jul 2, 2014

The original issue is old but I just had this problem, with the latest version of all components.

I tried lot of config & setup (assetDirs, etc) that I gathered around on Github issues / stackoverflow, but nothing did the trick for my problem.

The problem was like the original post, url(../images/bla.ext) was rewrote url(images/bla.ext) during cssmin.

The problem was trusting the yeoman configuration template. I just removed the "root" configuration, and it solved everything.

So from:
// The following *-min tasks produce minified files in the dist folder
cssmin: {
options: {
root: '<%= yeoman.app %>'
}
},

Set:
// The following *-min tasks produce minified files in the dist folder
cssmin: {
options: {
}
}

6 hours lost, made my day though /o/

@juanmhidalgo
Copy link

Thanks @Gamatora it works!

@terjekrogstad
Copy link

Nice one @Gamatora . Resolved my generator-angular-phonegap headache :)

@thalesfsp
Copy link

Solution:

  • From filerev, remove '<%= yeoman.dist %>/images/{,/}.{png,jpg,jpeg,gif,webp,svg}' in src;
  • From usemin, remove '<%= yeoman.dist %>/images' in options -> assetsDirs;

jplaza added a commit to datil/dinerico that referenced this issue Sep 20, 2014
@johnsonw
Copy link

I was having an issue with this as well and the assetsDirs fixed it for me:

usemin: {
  html: ['target/public/index.html'],
  css: ['target/public/assets/*.css'],
  options: {
    assetsDirs: ['target/public', 'target/public/assets']
  }
}

tserong added a commit to SUSE/calamari-clients that referenced this issue Jan 20, 2015
Without this, images are renamed, but the references to them in the CSS
aren't updated correctly, which prevents the SUSE logo in the footer
displaying.  For further discussion, see
yeoman/yeoman#824 (comment)

It's curious that this fix doesn't seem to be necessary for
dashboard/Gruntfile.js (are the files there not being renamed by rev?)

Signed-off-by: Tim Serong <tserong@suse.com>
dschi referenced this issue in sidneys/generator-ionic Jan 30, 2015
@Ouadie
Copy link

Ouadie commented Feb 20, 2015

V 1.3.3 and still have the background:url('.tmp/images/bg.png') instead of background:url('../images/bg.png') using the default gruntfile.js for angular-generator

@bmatto
Copy link

bmatto commented Mar 5, 2015

I'm having this issue as well @Ouadie - did you find any work around?

@Ouadie
Copy link

Ouadie commented Mar 6, 2015

For now I'm using $img-path:'../../../images;' instead of $img-path:'../images'; and it works for grunt serve and grunt build

@bmatto
Copy link

bmatto commented Mar 6, 2015

Thank you kind sir.

ghillert added a commit to ghillert/spring-xd-admin-ui-client that referenced this issue Apr 21, 2015
The Grunt-based build infrastructure is based on Yeoman's AngularJS support and then further customized. As part of `XD-1230`, this build process is then further integrated into the larger Spring XD Gradle build. Please see `README.md` for further details.

* Add AngularUI Router dependency
* Add UI-Router routes
* Add LESS support + UI Admin Styles
* Instead of customizing Bootstrap's `variables.less`, we instead import its styles into `main.less` and customize only the variables that changed. That way we can easily upgrade Bootstrap in the future
* Fix a `grunt-usemin` issue with images in CSS files
  - Use fix as detailed here: yeoman/yeoman#824 (comment)
  - See also issue: yeoman/grunt-usemin#242
* Exclude vendor CSS, we already import the Bootstrap CSS via `main.less`
* Don't use port 8080 for Karma tests in order to minimize conflicts with Tomcat
* Add "Loading Indicator" support using `angular-busy`
* Add Job launch support + Growl support + define XD Server URL globally
* Use Bootstrap fonts from the distribution
* Improve Job launch support
* Update `.gitignore`
* Update Nodejs dependencies, fix test dependencies
  - Running `npm install` should install all relevant dependencies from `package.json`
* Add Gradle build support
* Import CSS files as LESS resources in `main.less`
  - Otherwise you run into minification issues as Grunt's nsmin does not consider those CSS files
* Remove old `admin-ui`
* Improve resolving of the admin-ui URLs
  - http://localhost:9393/admin-ui --> http://localhost:9393/admin-ui/#/jobs/definitions
  - http://localhost:9393/admin-ui/ --> http://localhost:9393/admin-ui/#/jobs/definitions
* Add task `cleanDist`
* Improve Gradle build - Depend on `spring-xd-dirt:backgroundAdminServer`
* Fix `xd.ui.home` in `application.yml`
  - `xd.ui.home` in `application.yml` should contain a trailing slash
* Add `grunt-bower-task` to Grunt build
  - Allow Bower to be called via Grunt
* Test that the UI builds with `gradle npmInstall installGrunt build`
* Update Node dependency versions
* Fix "Required config property "bower-install.app.src" missing"
  - Bower Install - In `Gruntfile.js`, change config `html: '<%= yeoman.app %>/index.html',` to `src: '<%= yeoman.app %>/index.html',`
* Add Proxying to XD Admin Server via Grunt build
  - Add https://github.com/drewzboto/grunt-connect-proxy
* Better error messages when pulling Job Definitions
* Add `.bower_cache` directory local to project dir
* Add Karma shell scripts
  - I find these shell scripts quite useful when writing unit and e2e tests as you can configure Karma to keep running as a daemon (automatically re-running the tests of code-changes do occur)
* Add Grunt task `testfiles` - useful to prepare Spring XD test files
* Add Karma Safari launcher
* Add Unit and E2E tests
* Remove unnecessary files
  - .gitattributes
  - app/.buildignore
  - app/robots.txt
* Remove old loading Gif `loading.gif`
  - Remove unused related CSS
* Ensure we use only single quotes in JS files
* Improve Favicon support including mobile
* Remove main.css + main.css.map (autogenerated)
* Make sure LESS creates CSS files when executing `grunt serve`
* Update `.gitignore`
* Change Grunt Server Port to 8000
  - Port 9000 conflicts with Sonar
* Improve Gradle Build - `gradle build` will:
  - Install (if needed) node
  - Install (if needed) grunt
  - Download node dependencies for XD UI
  - Run the Grunt build
* `gradle clean` will remove all unnecessary spring-xd-ui folders (e.g. local node modules, bower files etc)
* Run Spring XD UI Grunt build on Eclipse STS import
  - Add task `afterEclipseImport`
  - See for details: https://issuetracker.springsource.com/browse/STS-2059
* Add `README.md`
* Fix live-reloading of Html files
* Fix copying of images in `Gruntfile.js`

XD-1229 Code Review changes

* Remove `.htaccess`
* Run E2E as part of the Gradle test task
* For distribution, copy Admin UI to `spring-xd-ui/dist`
tserong added a commit to SUSE/romana that referenced this issue Jun 25, 2015
Without this, images are renamed, but the references to them in the CSS
aren't updated correctly, which prevents the SUSE logo in the footer
displaying.  For further discussion, see
yeoman/yeoman#824 (comment)

It's curious that this fix doesn't seem to be necessary for
dashboard/Gruntfile.js (are the files there not being renamed by rev?)

Signed-off-by: Tim Serong <tserong@suse.com>
(cherry picked from commit 71b1cd791fe64aedc8c1cb766f37687075320e4e)
@viz
Copy link

viz commented Sep 23, 2015

just encountered this problem in a project created very recently using yeoman 1.4.8
I thought that I should post how I resolved it here for the benefit of others. I went to try @marcalj 's solution above, but the default config generated by yeoman looked like it was already doing that.

There was a subtle difference though. The default looked like:

usemin: {
  html: ['<%= yeoman.dist %>/client/!(bower_components){,*/}*.html'],
  css: ['<%= yeoman.dist %>/client/!(bower_components){,*/}*.css'],
  js: ['<%= yeoman.dist %>/client/!(bower_components){,*/}*.js'],
  options: {
    assetsDirs: [
      '<%= yeoman.dist %>/client',
      '<%= yeoman.dist %>/client/assets/images'
    ],

which didn't work (the asset reference in the stylesheet wasn't updated by usemin).

To get it working, I added the assets directory into the assetsDirs array:

usemin: {
  html: ['<%= yeoman.dist %>/client/!(bower_components){,*/}*.html'],
  css: ['<%= yeoman.dist %>/client/!(bower_components){,*/}*.css'],
  js: ['<%= yeoman.dist %>/client/!(bower_components){,*/}*.js'],
  options: {
    assetsDirs: [
      '<%= yeoman.dist %>/client',
      '<%= yeoman.dist %>/client/assets',
      '<%= yeoman.dist %>/client/assets/images'
    ],

which resolved the issue.

@Wirwing
Copy link

Wirwing commented Dec 21, 2015

Thanks @viz. adding assets directory did the trick!

@gugol2
Copy link

gugol2 commented Jul 26, 2016

None of the solutions here worked for me.
I am using generator-angular 0.15.1

This solved my problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests