From fa004d754ff03e3d418acdff3f84e4925551c320 Mon Sep 17 00:00:00 2001 From: Konstantin Raev Date: Fri, 28 Nov 2014 18:26:02 +1300 Subject: [PATCH] added a parameter to transform URLs without adding assets to webpack pipeline --- README.md | 19 +++++++++++++++++++ index.js | 4 ++++ test/urlTest.js | 3 +++ 3 files changed, 26 insertions(+) diff --git a/README.md b/README.md index fb29d042..e1d77663 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,25 @@ The result is: * `url(/image.png)` => `require("./image.png")` +### 'Skip require and prepend' urls + +If you don't want to process the images but rather want to transform the URLs use this parameter + +If a `skipRequireAndAddPath` query parameter is set, it will be prepended to the url and assets won't be added to webpack bundle: + +With a config like: + +``` javascript + loaders: [ + { test: /\.css$/, loader: "style-loader!css-loader?skipRequireAndAddPath=app/images" }, + ... + ] +``` + +The result is: + +* `url(/image.png)` => `require("app/images/image.png")` + ### SourceMaps To include SourceMaps set the `sourceMap` query param. diff --git a/index.js b/index.js index 1c00cec1..cf35f8cc 100644 --- a/index.js +++ b/index.js @@ -13,6 +13,7 @@ module.exports = function(content, map) { var query = loaderUtils.parseQuery(this.query); var root = query.root; var forceMinimize = query.minimize; + var skipRequireAndAddPath = query.skipRequireAndAddPath; var importLoaders = parseInt(query.importLoaders, 10) || 0; var minimize = typeof forceMinimize !== "undefined" ? !!forceMinimize : (this && this.minimize); var tree = csso.parse(content, "stylesheet"); @@ -46,6 +47,9 @@ module.exports = function(content, map) { var match = /^%CSSURL\[%(["']?(.*?)["']?)%\]CSSURL%$/.exec(JSON.parse('"' + str + '"')); var url = loaderUtils.parseString(match[2]); if(!loaderUtils.isUrlRequest(match[2], root)) return JSON.stringify(match[1]).replace(/^"|"$/g, ""); + if(skipRequireAndAddPath) { + return skipRequireAndAddPath + url; + } var idx = url.indexOf("?#"); if(idx < 0) idx = url.indexOf("#"); if(idx > 0) { diff --git a/test/urlTest.js b/test/urlTest.js index dfa46a1a..4aa7718c 100644 --- a/test/urlTest.js +++ b/test/urlTest.js @@ -107,6 +107,9 @@ describe("url", function() { test("background img absolute with root", ".class { background: green url(/img.png) xyz }", [ [1, ".class { background: green url({./img.png}) xyz }", ""] ], "?root=."); + test("background img with prepended path", ".class { background: green url(img.png) xyz }", [ + [1, ".class { background: green url(app/images/img.png) xyz }", ""] + ], "?skipRequireAndAddPath=app/images/"); test("background img external", ".class { background: green url(data:image/png;base64,AAA) url(http://example.com/image.jpg) url(//example.com/image.png) xyz }", [ [1, ".class { background: green url(data:image/png;base64,AAA) url(http://example.com/image.jpg) url(//example.com/image.png) xyz }", ""]