diff --git a/README.md b/README.md index a858091a..d19bd58f 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![chat][chat]][chat-url]
- Usage -The `css-loader` interprets `@import` and `url()` like `requires`. +The `css-loader` interprets `@import` and `url()` like `import/require()` +and will resolve them. -Use the loader either via your webpack config, CLI or inline. +Good loaders for requiring your assets are the [file-loader](https://github.com/webpack/file-loader) +and the [url-loader](https://github.com/webpack/url-loader) which you should specify in your config (see [below](https://github.com/michael-ciniawsky/css-loader#assets)). -### Via webpack config (recommended) +**file.css** +```js +import css from 'file.css'; +``` **webpack.config.js** ```js @@ -43,109 +48,138 @@ module.exports = { } ``` -**In your application** -```js -import css from 'file.css'; -``` - -### CLI +### `toString` -```bash -webpack --module-bind 'css=style-loader!css-loader' -``` +You can also use the css-loader results directly as string, such as in Angular's component style. -**In your application** +**webpack.config.js** ```js -import css from 'file.css'; +{ +   test: /\.css$/, +   use: [ +     'to-string-loader', + 'css-loader' +   ] +} ``` -### Inline +or -**In your application** ```js -import css from 'style-loader!css-loader!./file.css'; +const css = require('./test.css').toString(); + +console.log(css); // {String} ``` -

Options

+If there are SourceMaps, they will also be included in the result string. -`@import` and `url()` are interpreted like `import` and will be resolved by the css-loader. -Good loaders for requiring your assets are the [file-loader](https://github.com/webpack/file-loader) -and the [url-loader](https://github.com/webpack/url-loader) which you should specify in your config (see below). +

Options

-To be compatible with existing css files (if not in CSS Module mode): +|Name|Type|Default|Description| +|:--:|:--:|:-----:|:----------| +|**`root`**|`{String}`|`/`|Path to resolve URLs, URLs starting with `/` will not be translated| +|**`url`**|`{Boolean}`|`true`| Enable/Disable `url()` handling| +|**`alias`**|`{Object}`|`{}`|Create aliases to import certain modules more easily| +|**`import`** |`{Boolean}`|`true`| Enable/Disable @import handling| +|**`modules`**|`{Boolean}`|`false`|Enable/Disable CSS Modules| +|**`minimize`**|`{Boolean\|Object}`|`false`|Enable/Disable minification| +|**`sourceMap`**|`{Boolean}`|`false`|Enable/Disable Sourcemaps| +|**`camelCase`**|`{Boolean\|String}`|`false`|Export Classnames in CamelCase| +|**`importLoaders`**|`{Number}`|`0`|Number of loaders applied before CSS loader| -* `url(image.png)` => `require('./image.png')` -* `url(~module/image.png)` => `require('module/image.png')` +### `root` -

Options

+For URLs that start with a `/`, the default behavior is to not translate them. -|Name|Default|Description| -|:--:|:-----:|:----------| -|**`root`**|`/`|Path to resolve URLs, URLs starting with `/` will not be translated| -|**`modules`**|`false`|Enable/Disable CSS Modules| -|**`import`** |`true`| Enable/Disable @import handling| -|**`url`**|`true`| Enable/Disable `url()` handling| -|**`minimize`**|`false`|Enable/Disable minification| -|**`sourceMap`**|`false`|Enable/Disable Sourcemaps| -|**`camelCase`**|`false`|Export Classnames in CamelCase| -|**`importLoaders`**|`0`|Number of loaders applied before CSS loader| -|**`alias`**|`{}`|Create aliases to import certain modules more easily| +`url(/image.png) => url(/image.png)` -The following webpack config can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as [Data URLs](https://tools.ietf.org/html/rfc2397) and copy larger files to the output directory. +If a `root` query parameter is set, however, it will be prepended to the URL +and then translated. **webpack.config.js** ```js -module.exports = { - module: { - rules: [ - { - test: /\.css$/, - use: [ 'style-loader', 'css-loader' ] - }, - { - test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, - loader: 'url-loader', - options: { - limit: 10000 - } - } - ] - } -}; +{ + loader: 'css-loader', + options: { root: '.' } +} +``` + +`url(/image.png)` => `require('./image.png')` + +Using 'Root-relative' urls is not recommended. You should only use it for legacy CSS files. + +### `url` + +To disable `url()` resolving by `css-loader` set the option to `false`. + +To be compatible with existing css files (if not in CSS Module mode). + +``` +url(image.png) => require('./image.png') +url(~module/image.png) => require('module/image.png') ``` -### Root +### `alias` -For URLs that start with a `/`, the default behavior is to not translate them: +Rewrite your urls with alias, this is useful when it's hard to change url paths of your input files, for example, when you're using some css / sass files in another package (bootstrap, ratchet, font-awesome, etc.). -* `url(/image.png)` => `url(/image.png)` +`css-loader`'s `alias` follows the same syntax as webpack's `resolve.alias`, you can see the details at the [resolve docs] (https://webpack.js.org/configuration/resolve/#resolve-alias) -If a `root` query parameter is set, however, it will be prepended to the URL -and then translated: +**file.scss** +```css +@charset "UTF-8"; +@import "bootstrap"; +``` **webpack.config.js** ```js -rules: [ - { - test: /\.css$/, - use: [ - 'style-loader', - { - loader: 'css-loader', - options: { root: '.' } +{ + test: /\.scss$/, + use: [ + { + loader: "style-loader" + }, + { + loader: "css-loader", + options: { + alias: { + "../fonts/bootstrap": "bootstrap-sass/assets/fonts/bootstrap" + } } - ] - } -] + }, + { + loader: "sass-loader", + options: { + includePaths: [ + path.resolve("./node_modules/bootstrap-sass/assets/stylesheets") + ] + } + } + ] +} ``` -* `url(/image.png)` => `require('./image.png')` +Check out this [working bootstrap example](https://github.com/bbtfr/webpack2-bootstrap-sass-sample). -Using 'Root-relative' urls is not recommended. You should only use it for legacy CSS files. +### `import` + +To disable `@import` resolving by `css-loader` set the option to `false` + +```css +@import url('https://fonts.googleapis.com/css?family=Roboto'); +``` -### CSS Scope +> :waning: Use with caution, since this disables resolving for **all** `@import`s -By default CSS exports all class names into a global selector scope. Styles can be locally scoped to avoid globally scoping styles. +### [`modules`](https://github.com/css-modules/css-modules) + +The query parameter `modules` enables the **CSS Modules** spec. + +This enables local scoped CSS by default. (You can switch it off with `:global(...)` or `:global` for selectors and/or rules.). + +#### `Scope` + +By default CSS exports all classnames into a global selector scope. Styles can be locally scoped to avoid globally scoping styles. The syntax `:local(.className)` can be used to declare `className` in the local scope. The local identifiers are exported by the module. @@ -153,7 +187,6 @@ With `:local` (without brackets) local mode can be switched on for this selector The loader replaces local selectors with unique identifiers. The choosen unique identifiers are exported by the module. -**app.css** ```css :local(.className) { background: red; } :local .className { color: green; } @@ -161,17 +194,16 @@ The loader replaces local selectors with unique identifiers. The choosen unique :local .className .subClass :global(.global-class-name) { color: blue; } ``` -**app.bundle.css** -``` css +```css ._23_aKvs-b8bW2Vg3fwHozO { background: red; } ._23_aKvs-b8bW2Vg3fwHozO { color: green; } ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 { color: green; } ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name { color: blue; } ``` -> Note: Identifiers are exported +> :information_source: Identifiers are exported -``` js +```js exports.locals = { className: '_23_aKvs-b8bW2Vg3fwHozO', subClass: '_13LGdX8RMStbBE9w-t0gZ1' @@ -180,13 +212,14 @@ exports.locals = { CamelCase is recommended for local selectors. They are easier to use in the within the imported JS module. -`url()` URLs in block scoped (`:local .abc`) rules behave like requests in modules: +`url()` URLs in block scoped (`:local .abc`) rules behave like requests in modules. -* `./file.png` instead of `file.png` -* `module/file.png` instead of `~module/file.png` +``` +file.png => ./file.png +~module/file.png => module/file.png +``` You can use `:local(#someId)`, but this is not recommended. Use classes instead of ids. - You can configure the generated ident with the `localIdentName` query parameter (default `[hash:base64]`). **webpack.config.js** @@ -205,40 +238,29 @@ You can configure the generated ident with the `localIdentName` query parameter } ``` -You can also specify the absolute path to your custom `getLocalIdent` function to generate classname based on a different schema. This requires `webpack >= 2.2.1` (it supports functions in the `options` object). For example: +You can also specify the absolute path to your custom `getLocalIdent` function to generate classname based on a different schema. This requires `webpack >= 2.2.1` (it supports functions in the `options` object). **webpack.config.js** ```js { - test: /\.css$/, - use: [ - { - loader: 'css-loader', - options: { - modules: true, - localIdentName: '[path][name]__[local]--[hash:base64:5]', - getLocalIdent: (context, localIdentName, localName, options) => { - return 'whatever_random_class_name' - } - } + loader: 'css-loader', + options: { + modules: true, + localIdentName: '[path][name]__[local]--[hash:base64:5]', + getLocalIdent: (context, localIdentName, localName, options) => { + return 'whatever_random_class_name' } - ] + } } ``` -Note: For prerendering with extract-text-webpack-plugin you should use `css-loader/locals` instead of `style-loader!css-loader` **in the prerendering bundle**. It doesn't embed CSS but only exports the identifier mappings. +> :information_source: For prerendering with extract-text-webpack-plugin you should use `css-loader/locals` instead of `style-loader!css-loader` **in the prerendering bundle**. It doesn't embed CSS but only exports the identifier mappings. -### [CSS Modules](https://github.com/css-modules/css-modules) +#### `Composing` -The query parameter `modules` enables the **CSS Modules** spec. +When declaring a local classname you can compose a local class from another local classname. -This enables local scoped CSS by default. (You can switch it off with `:global(...)` or `:global` for selectors and/or rules.) - -### CSS Composing - -When declaring a local class name you can compose a local class from another local class name. - -``` css +```css :local(.className) { background: red; color: yellow; @@ -250,7 +272,7 @@ When declaring a local class name you can compose a local class from another loc } ``` -This doesn't result in any change to the CSS itself but exports multiple class names: +This doesn't result in any change to the CSS itself but exports multiple classnames. ```js exports.locals = { @@ -270,18 +292,18 @@ exports.locals = { } ``` -### Importing CSS Locals +#### `Importing` -To import a local class name from another module: +To import a local classname from another module. -``` css +```css :local(.continueButton) { composes: button from 'library/button.css'; background: red; } ``` -``` css +```css :local(.nameEdit) { composes: edit highlight from './edit.css'; background: red; @@ -290,7 +312,7 @@ To import a local class name from another module: To import from multiple modules use multiple `composes:` rules. -``` css +```css :local(.className) { composes: edit hightlight from './edit.css'; composes: button from 'module/button.css'; @@ -299,177 +321,159 @@ To import from multiple modules use multiple `composes:` rules. } ``` -### SourceMaps +### `minimize` -To include Sourcemaps set the `sourceMap` query param. +By default the css-loader minimizes the css if specified by the module system. -I. e. the extract-text-webpack-plugin can handle them. +In some cases the minification is destructive to the css, so you can provide your own options to the minifier if needed. cssnano is used for minification and you find a [list of options here](http://cssnano.co/options/). -They are not enabled by default because they expose a runtime overhead and increase in bundle size (JS SourceMap do not). In addition to that relative paths are buggy and you need to use an absolute public path which include the server URL. +You can also disable or enforce minification with the `minimize` query parameter. **webpack.config.js** ```js { - test: /\.css$/, - use: [ - { - loader: 'css-loader', - options: { - sourceMap: true - } - } - ] + loader: 'css-loader', + options: { + minimize: true || {/* CSSNano Options */} + } } ``` -### toString +### `sourceMap` -You can also use the css-loader results directly as string, such as in Angular's component style. +To include source maps set the `sourceMap` option. -**webpack.config.js** +I. e. the extract-text-webpack-plugin can handle them. +They are not enabled by default because they expose a runtime overhead and increase in bundle size (JS source maps do not). In addition to that relative paths are buggy and you need to use an absolute public path which include the server URL. + +**webpack.config.js** ```js { -   test: /\.css$/, -   use: [ -     { -       loaders: ['to-string-loader', 'css-loader'] -     } -   ] + loader: 'css-loader', + options: { + sourceMap: true + } } ``` -or - -```js -const cssText = require('./test.css').toString(); - -console.log(cssText); -``` +### `camelCase` -If there are SourceMaps, they will also be included in the result string. +By default, the exported JSON keys mirror the class names. If you want to camelize class names (useful in JS), pass the query parameter `camelCase` to css-loader. -### ImportLoaders +|Name|Type|Description| +|:--:|:--:|:----------| +|**`true`**|`{Boolean}`|Class names will be camelized| +|**`'dashes'`**|`{String}`|Only dashes in class names will be camelized| +|**`'only'`** |`{String}`|Introduced in `0.27.1`. Class names will be camelized, the original class name will be removed from the locals| +|**`'dashesOnly'`**|`{String}`|Introduced in `0.27.1`. Dashes in class names will be camelized, the original class name will be removed from the locals| -The query parameter `importLoaders` allow to configure which loaders should be applied to `@import`ed resources. +**file.css** +```css +.class-name {} +``` -`importLoaders`: That many loaders after the css-loader are used to import resources. +**file.js** +```js +import { className } from 'file.css'; +``` **webpack.config.js** ```js { - test: /\.css$/, - use: [ - { - loader: 'css-loader', - options: { - importLoaders: 1 - } - }, - 'postcss-loader' - ] + loader: 'css-loader', + options: { + camelCase: true + } } ``` -This may change in the future, when the module system (i. e. webpack) supports loader matching by origin. +### `importLoaders` -### Minification - -By default the css-loader minimizes the css if specified by the module system. - -In some cases the minification is destructive to the css, so you can provide some options to it. cssnano is used for minification and you find a [list of options here](http://cssnano.co/options/). - -You can also disable or enforce minification with the `minimize` query parameter. +The query parameter `importLoaders` allows to configure how many loaders before `css-loader` should be applied to `@import`ed resources. **webpack.config.js** ```js { test: /\.css$/, use: [ + 'style-loader', { loader: 'css-loader', options: { - minimize: true || {/* CSSNano Options */} + importLoaders: 1 // 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader } - } + }, + 'postcss-loader', + 'sass-loader' ] } ``` -### CamelCase +This may change in the future, when the module system (i. e. webpack) supports loader matching by origin. -By default, the exported JSON keys mirror the class names. If you want to camelize class names (useful in JS), pass the query parameter `camelCase` to css-loader. +

Examples

-#### Possible Options +### Assets -|Option|Description| -|:----:|:--------| -|**`true`**|Class names will be camelized| -|**`'dashes'`**|Only dashes in class names will be camelized| -|**`'only'`** |Introduced in `0.27.1`. Class names will be camelized, the original class name will be removed from the locals| -|**`'dashesOnly'`**|Introduced in `0.27.1`. Dashes in class names will be camelized, the original class name will be removed from the locals| +The following `webpack.config.js` can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as [Data URLs](https://tools.ietf.org/html/rfc2397) and copy larger files to the output directory. **webpack.config.js** ```js -{ - test: /\.css$/, - use: [ - { - loader: 'css-loader', - options: { - camelCase: true +module.exports = { + module: { + rules: [ + { + test: /\.css$/, + use: [ 'style-loader', 'css-loader' ] + }, + { + test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, + loader: 'url-loader', + options: { + limit: 10000 + } } - } - ] + ] + } } ``` -```css -.class-name {} -``` - -```js -import { className } from 'file.css'; -``` - -### Alias +### Extract -Rewrite your urls with alias, this is useful when it's hard to change url paths of your input files, for example, when you're using some css / sass files in another package (bootstrap, ratchet, font-awesome, etc.). - -#### Possible Options - -css-loader's `alias` follows the same syntax as webpack's `resolve.alias`, you can see the details at: https://webpack.js.org/configuration/resolve/#resolve-alias +For production builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on. This can be achieved by using the [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) to extract the CSS when running in production mode. **webpack.config.js** ```js -{ - test: /\.scss$/, - use: [{ - loader: "style-loader" - }, { - loader: "css-loader", - options: { - alias: { - "../fonts/bootstrap": "bootstrap-sass/assets/fonts/bootstrap" - } - } - }, { - loader: "sass-loader", - options: { - includePaths: [ - path.resolve("./node_modules/bootstrap-sass/assets/stylesheets") +const env = process.env.NODE_ENV + +const ExtractTextPlugin = require('extract-text-webpack-plugin') + +module.exports = { + module: { + rules: [ + { + test: /\.css$/, + use: env === 'production' + ? ExtractTextPlugin.extract({ + fallback: 'style-loader' + use: [ 'css-loader' ] + }) + : [ 'style-loader', 'css-loader' ] + }, + ] + }, + plugins: env === 'production' + ? [ + new ExtractTextPlugin({ + filename: '[name].css' + }) ] - } - }] + : [] + ] } ``` -```scss -@charset "UTF-8"; -@import "bootstrap"; -``` -Check out this [working bootstrap example](https://github.com/bbtfr/webpack2-bootstrap-sass-sample). -

Maintainers

@@ -477,29 +481,49 @@ Check out this [working bootstrap example](https://github.com/bbtfr/webpack2-boo + + + + +
+ src="https://github.com/bebraw.png?v=3&s=150">
Juho Vepsäläinen
+ src="https://github.com/d3viant0ne.png?v=3&s=150">
Joshua Wiens
+ src="https://github.com/SpaceK33z.png?v=3&s=150">
Kees Kluskens
+ src="https://github.com/TheLarkInn.png?v=3&s=150">
Sean Larkin
+ +
+ Michael Ciniawsky +
+ +
+ Evilebot Tnawi +
+ +
+ Joscha Feth +
diff --git a/lib/css-base.js b/lib/css-base.js index b67c1d74..59af87df 100644 --- a/lib/css-base.js +++ b/lib/css-base.js @@ -54,7 +54,7 @@ function cssWithMappingToString(item, useSourceMap) { return content; } - if (useSourceMap) { + if (useSourceMap && typeof btoa === 'function') { var sourceMapping = toComment(cssMapping); var sourceURLs = cssMapping.sources.map(function (source) { return '/*# sourceURL=' + cssMapping.sourceRoot + source + ' */' @@ -68,8 +68,9 @@ function cssWithMappingToString(item, useSourceMap) { // Adapted from convert-source-map (MIT) function toComment(sourceMap) { - var base64 = new Buffer(JSON.stringify(sourceMap)).toString('base64'); - var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; + // eslint-disable-next-line no-undef + var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))); + var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; - return '/*# ' + data + ' */'; + return '/*# ' + data + ' */'; } diff --git a/lib/processCss.js b/lib/processCss.js index 181f7a2a..2c2fea6d 100644 --- a/lib/processCss.js +++ b/lib/processCss.js @@ -13,6 +13,7 @@ var localByDefault = require("postcss-modules-local-by-default"); var extractImports = require("postcss-modules-extract-imports"); var modulesScope = require("postcss-modules-scope"); var modulesValues = require("postcss-modules-values"); +var valueParser = require('postcss-value-parser'); var parserPlugin = postcss.plugin("css-loader-parser", function(options) { return function(css) { @@ -23,21 +24,24 @@ var parserPlugin = postcss.plugin("css-loader-parser", function(options) { function replaceImportsInString(str) { if(options.import) { - var tokens = str.split(/(\S+)/); - tokens = tokens.map(function (token) { + var tokens = valueParser(str); + tokens.walk(function (node) { + if (node.type !== 'word') { + return; + } + var token = node.value; var importIndex = imports["$" + token]; if(typeof importIndex === "number") { - return "___CSS_LOADER_IMPORT___" + importIndex + "___"; + node.value = "___CSS_LOADER_IMPORT___" + importIndex + "___"; } - return token; - }); - return tokens.join(""); + }) + return tokens.toString(); } return str; } if(options.import) { - css.walkAtRules("import", function(rule) { + css.walkAtRules(/import/i, function(rule) { var values = Tokenizer.parseValues(rule.params); var url = values.nodes[0].nodes[0]; if(url.type === "url") { @@ -98,7 +102,10 @@ var parserPlugin = postcss.plugin("css-loader-parser", function(options) { break; case "url": if (options.url && !/^#/.test(item.url) && loaderUtils.isUrlRequest(item.url, options.root)) { - item.stringType = ""; + // Don't remove quotes around url when contain space + if (item.url.indexOf(" ") === -1) { + item.stringType = ""; + } delete item.innerSpacingBefore; delete item.innerSpacingAfter; var url = item.url; @@ -153,6 +160,8 @@ module.exports = function processCss(inputSource, inputMap, options, callback) { mode: options.mode, rewriteUrl: function(global, url) { if(parserOptions.url){ + url = url.trim(" "); + if(!loaderUtils.isUrlRequest(url, root)) { return url; } diff --git a/package.json b/package.json index 47974860..13ab19c9 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "postcss-modules-local-by-default": "^1.0.1", "postcss-modules-scope": "^1.0.0", "postcss-modules-values": "^1.1.0", + "postcss-value-parser": "^3.3.0", "source-list-map": "^0.1.7" }, "devDependencies": { diff --git a/test/cssBaseTest.js b/test/cssBaseTest.js index de176a66..01b2a2ee 100644 --- a/test/cssBaseTest.js +++ b/test/cssBaseTest.js @@ -1,8 +1,26 @@ -/*globals describe it*/ +/*eslint-env mocha*/ var base = require("../lib/css-base"); describe("css-base", function() { + before(function() { + global.btoa = function btoa(str) { + var buffer = null; + + if (str instanceof Buffer) { + buffer = str; + } else { + buffer = new Buffer(str.toString(), 'binary'); + } + + return buffer.toString('base64'); + } + }) + + after(function () { + global.btoa = null; + }) + it("should toString a single module", function() { var m = base(); m.push([1, "body { a: 1; }", ""]); @@ -46,4 +64,17 @@ describe("css-base", function() { }]); m.toString().should.be.eql("body { a: 1; }\n/*# sourceURL=webpack://./path/to/test.scss */\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJmaWxlIjoidGVzdC5zY3NzIiwic291cmNlcyI6WyIuL3BhdGgvdG8vdGVzdC5zY3NzIl0sIm1hcHBpbmdzIjoiQUFBQTsiLCJzb3VyY2VSb290Ijoid2VicGFjazovLyJ9 */"); }); + it("should toString without source mapping if btoa not avalibale", function() { + global.btoa = null; + var m = base(true); + m.push([1, "body { a: 1; }", "", { + file: "test.scss", + sources: [ + './path/to/test.scss' + ], + mappings: "AAAA;", + sourceRoot: "webpack://" + }]); + m.toString().should.be.eql("body { a: 1; }"); + }); }); diff --git a/test/importTest.js b/test/importTest.js index 19efac8b..52c94510 100644 --- a/test/importTest.js +++ b/test/importTest.js @@ -9,6 +9,12 @@ describe("import", function() { ], "", { "./test.css": [[2, ".test{a: b}", ""]] }); + test("import camelcase", "@IMPORT url(test.css);\n.class { a: b c d; }", [ + [2, ".test{a: b}", ""], + [1, ".class { a: b c d; }", ""] + ], "", { + "./test.css": [[2, ".test{a: b}", ""]] + }); test("import with string", "@import \"test.css\";\n.class { a: b c d; }", [ [2, ".test{a: b}", ""], [1, ".class { a: b c d; }", ""] diff --git a/test/moduleTestCases/urls/expected.css b/test/moduleTestCases/urls/expected.css index 50416ce3..ea4dba76 100644 --- a/test/moduleTestCases/urls/expected.css +++ b/test/moduleTestCases/urls/expected.css @@ -1,6 +1,8 @@ ._a_ { background: url({./module}); background: url({./module}); + background: url("{./module module}"); + background: url('{./module module}'); background: url({./module}); background: url({./module}#?iefix); background: url("#hash"); diff --git a/test/moduleTestCases/urls/source.css b/test/moduleTestCases/urls/source.css index beac30e6..1c58afe7 100644 --- a/test/moduleTestCases/urls/source.css +++ b/test/moduleTestCases/urls/source.css @@ -1,6 +1,8 @@ .a { background: url(./module); background: url("./module"); + background: url("./module module"); + background: url('./module module'); background: url('./module'); background: url("./module#?iefix"); background: url("#hash"); diff --git a/test/simpleTest.js b/test/simpleTest.js index 8ff5a662..a8899263 100644 --- a/test/simpleTest.js +++ b/test/simpleTest.js @@ -18,18 +18,32 @@ describe("simple", function() { test("simple2", ".class { a: b c d; }\n.two {}", [ [1, ".class { a: b c d; }\n.two {}", ""] ]); + test("escape characters (uppercase)", ".class { content: \"\\F10C\" }", [ + [1, ".class { content: \"\\F10C\" }", ""] + ]); + // Need uncomment after resolve https://github.com/css-modules/postcss-modules-local-by-default/issues/108 + /*test("escape characters (lowercase)", ".class { content: \"\\f10C\" }", [ + [1, ".class { content: \"\\f10C\" }", ""] + ]);*/ + // Need uncomment after resolve https://github.com/mathiasbynens/cssesc/issues/10 + /*test("escape characters (two)", ".class { content: \"\\F10C \\F10D\" }", [ + [1, ".class { content: \"\\F10C \\F10D\" }", ""] + ]);*/ testMinimize("minimized simple", ".class { a: b c d; }", [ [1, ".class{a:b c d}", ""] ]); - testError("error formatting", ".some {\n invalid css;\n}", function(err) { - assert.equal(err.message, [ - 'Unknown word (2:2)', - '', - ' 1 | .some {', - '> 2 | invalid css;', - ' | ^', - ' 3 | }', - '', - ].join('\n')); - }); + test("charset directive", "@charset \"UTF-8\";\n .class { a: b c d; }", [ + [1, "@charset \"UTF-8\";\n .class { a: b c d; }", ""] + ]); + testError("error formatting", ".some {\n invalid css;\n}", function(err) { + assert.equal(err.message, [ + 'Unknown word (2:2)', + '', + ' 1 | .some {', + '> 2 | invalid css;', + ' | ^', + ' 3 | }', + '', + ].join('\n')); + }); }); diff --git a/test/sourceMapTest.js b/test/sourceMapTest.js index 39401e95..23ac5dc8 100644 --- a/test/sourceMapTest.js +++ b/test/sourceMapTest.js @@ -44,6 +44,40 @@ describe("source maps", function() { version: 3 }] ]); + testMap("generate sourceMap (1 loader, data url)", ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,\"); }", undefined, { + loaders: [{request: "/path/css-loader"}], + options: { context: "/" }, + resource: "/folder/test.css", + request: "/path/css-loader!/folder/test.css", + query: "?sourceMap" + }, [ + [1, ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,\"); }", "", { + file: 'test.css', + mappings: 'AAAA,SAAS,6WAA6W,EAAE', + names: [], + sourceRoot: '', + sources: [ '/folder/test.css' ], + sourcesContent: [ '.class { background-image: url("data:image/svg+xml;charset=utf-8,"); }' ], + version: 3 + }] + ]); + testMap("generate sourceMap (1 loader, encoded data url)", ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2042%2026%27%20fill%3D%27%23007aff%27%3E%3Crect%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%271%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2711%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2712%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2722%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2723%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3C%2Fsvg%3E\"); }", undefined, { + loaders: [{request: "/path/css-loader"}], + options: { context: "/" }, + resource: "/folder/test.css", + request: "/path/css-loader!/folder/test.css", + query: "?sourceMap" + }, [ + [1, ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2042%2026%27%20fill%3D%27%23007aff%27%3E%3Crect%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%271%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2711%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2712%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2722%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2723%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3C%2Fsvg%3E\"); }", "", { + file: 'test.css', + mappings: 'AAAA,SAAS,mmBAAmmB,EAAE', + names: [], + sourceRoot: '', + sources: [ '/folder/test.css' ], + sourcesContent: [ '.class { background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2042%2026%27%20fill%3D%27%23007aff%27%3E%3Crect%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%271%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2711%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2712%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2722%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2723%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3C%2Fsvg%3E"); }' ], + version: 3 + }] + ]); testMap("generate sourceMap (2 loaders)", ".class { a: b c d; }", undefined, { loaders: [{request: "/path/css-loader"}, {request: "/path/sass-loader"}], options: { context: "/" }, diff --git a/test/urlTest.js b/test/urlTest.js index b54bf9a8..e25a4b77 100644 --- a/test/urlTest.js +++ b/test/urlTest.js @@ -12,6 +12,15 @@ describe("url", function() { test("background img 3", ".class { background: green url( 'img.png' ) xyz }", [ [1, ".class { background: green url({./img.png}) xyz }", ""] ]); + test("background img 4", ".class { background: green url( img.png ) xyz }", [ + [1, ".class { background: green url({./img.png}) xyz }", ""] + ]); + test("background img contain space in name", ".class { background: green url( \"img img.png\" ) xyz }", [ + [1, ".class { background: green url(\"{./img img.png}\") xyz }", ""] + ]); + test("background 2 img contain space in name", ".class { background: green url( 'img img.png' ) xyz }", [ + [1, ".class { background: green url('{./img img.png}') xyz }", ""] + ]); test("background img absolute", ".class { background: green url(/img.png) xyz }", [ [1, ".class { background: green url(/img.png) xyz }", ""] ]); @@ -26,10 +35,18 @@ describe("url", function() { ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,\") }", [ [1, ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,\") }", ""] ]); + test("background img external encoded data", + ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2042%2026%27%20fill%3D%27%2523007aff%27%3E%3Crect%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%271%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2711%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2712%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2722%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2723%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3C%2Fsvg%3E\") }", [ + [1, ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2042%2026%27%20fill%3D%27%2523007aff%27%3E%3Crect%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%271%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2711%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2712%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2722%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2723%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3C%2Fsvg%3E\") }", ""] + ]); test("data url in filter", ".class { filter: url('data:image/svg+xml;charset=utf-8,#filter'); }", [ [1, ".class { filter: url('data:image/svg+xml;charset=utf-8,#filter'); }", ""] ]); + test("encoded data url in filter", + ".class { filter: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%5C%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%5C%22%3E%3Cfilter%20id%3D%5C%22filter%5C%22%3E%3CfeGaussianBlur%20in%3D%5C%22SourceAlpha%5C%22%20stdDeviation%3D%5C%220%5C%22%20%2F%3E%3CfeOffset%20dx%3D%5C%221%5C%22%20dy%3D%5C%222%5C%22%20result%3D%5C%22offsetblur%5C%22%20%2F%3E%3CfeFlood%20flood-color%3D%5C%22rgba(255%2C255%2C255%2C1)%5C%22%20%2F%3E%3CfeComposite%20in2%3D%5C%22offsetblur%5C%22%20operator%3D%5C%22in%5C%22%20%2F%3E%3CfeMerge%3E%3CfeMergeNode%20%2F%3E%3CfeMergeNode%20in%3D%5C%22SourceGraphic%5C%22%20%2F%3E%3C%2FfeMerge%3E%3C%2Ffilter%3E%3C%2Fsvg%3E%23filter'); }", [ + [1, ".class { filter: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%5C%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%5C%22%3E%3Cfilter%20id%3D%5C%22filter%5C%22%3E%3CfeGaussianBlur%20in%3D%5C%22SourceAlpha%5C%22%20stdDeviation%3D%5C%220%5C%22%20%2F%3E%3CfeOffset%20dx%3D%5C%221%5C%22%20dy%3D%5C%222%5C%22%20result%3D%5C%22offsetblur%5C%22%20%2F%3E%3CfeFlood%20flood-color%3D%5C%22rgba(255%2C255%2C255%2C1)%5C%22%20%2F%3E%3CfeComposite%20in2%3D%5C%22offsetblur%5C%22%20operator%3D%5C%22in%5C%22%20%2F%3E%3CfeMerge%3E%3CfeMergeNode%20%2F%3E%3CfeMergeNode%20in%3D%5C%22SourceGraphic%5C%22%20%2F%3E%3C%2FfeMerge%3E%3C%2Ffilter%3E%3C%2Fsvg%3E%23filter'); }", ""] + ]); test("filter hash", ".highlight { filter: url(#highlight); }", [ [1, ".highlight { filter: url(#highlight); }", ""] @@ -63,6 +80,15 @@ describe("url", function() { test("background img 3 with url", ".class { background: green url( 'img.png' ) xyz }", [ [1, ".class { background: green url( 'img.png' ) xyz }", ""] ], "?-url"); + test("background img 4 with url", ".class { background: green url( img.png ) xyz }", [ + [1, ".class { background: green url( img.png ) xyz }", ""] + ], "?-url"); + test("background img with url contain space in name", ".class { background: green url( \"img img.png\" ) xyz }", [ + [1, ".class { background: green url( \"img img.png\" ) xyz }", ""] + ], "?-url"); + test("background 2 img with url contain space in name", ".class { background: green url( 'img img.png' ) xyz }", [ + [1, ".class { background: green url( 'img img.png' ) xyz }", ""] + ], "?-url"); test("background img absolute with url", ".class { background: green url(/img.png) xyz }", [ [1, ".class { background: green url(/img.png) xyz }", ""] ], "?-url"); @@ -74,10 +100,18 @@ describe("url", function() { ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,\") }", [ [1, ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,\") }", ""] ], "?-url"); + test("background img external encoded data with url", + ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2042%2026%27%20fill%3D%27%2523007aff%27%3E%3Crect%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%271%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2711%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2712%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2722%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2723%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3C%2Fsvg%3E\") }", [ + [1, ".class { background-image: url(\"data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2042%2026%27%20fill%3D%27%2523007aff%27%3E%3Crect%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%271%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2711%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2712%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3Crect%20y%3D%2722%27%20width%3D%274%27%20height%3D%274%27%2F%3E%3Crect%20x%3D%278%27%20y%3D%2723%27%20width%3D%2734%27%20height%3D%272%27%2F%3E%3C%2Fsvg%3E\") }", ""] + ], "?-url"); test("data url in filter with url", ".class { filter: url('data:image/svg+xml;charset=utf-8,#filter'); }", [ [1, ".class { filter: url('data:image/svg+xml;charset=utf-8,#filter'); }", ""] ], "?-url"); + test("encoded data url in filter with url", + ".class { filter: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%5C%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%5C%22%3E%3Cfilter%20id%3D%5C%22filter%5C%22%3E%3CfeGaussianBlur%20in%3D%5C%22SourceAlpha%5C%22%20stdDeviation%3D%5C%220%5C%22%20%2F%3E%3CfeOffset%20dx%3D%5C%221%5C%22%20dy%3D%5C%222%5C%22%20result%3D%5C%22offsetblur%5C%22%20%2F%3E%3CfeFlood%20flood-color%3D%5C%22rgba(255%2C255%2C255%2C1)%5C%22%20%2F%3E%3CfeComposite%20in2%3D%5C%22offsetblur%5C%22%20operator%3D%5C%22in%5C%22%20%2F%3E%3CfeMerge%3E%3CfeMergeNode%20%2F%3E%3CfeMergeNode%20in%3D%5C%22SourceGraphic%5C%22%20%2F%3E%3C%2FfeMerge%3E%3C%2Ffilter%3E%3C%2Fsvg%3E%23filter'); }", [ + [1, ".class { filter: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%5C%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%5C%22%3E%3Cfilter%20id%3D%5C%22filter%5C%22%3E%3CfeGaussianBlur%20in%3D%5C%22SourceAlpha%5C%22%20stdDeviation%3D%5C%220%5C%22%20%2F%3E%3CfeOffset%20dx%3D%5C%221%5C%22%20dy%3D%5C%222%5C%22%20result%3D%5C%22offsetblur%5C%22%20%2F%3E%3CfeFlood%20flood-color%3D%5C%22rgba(255%2C255%2C255%2C1)%5C%22%20%2F%3E%3CfeComposite%20in2%3D%5C%22offsetblur%5C%22%20operator%3D%5C%22in%5C%22%20%2F%3E%3CfeMerge%3E%3CfeMergeNode%20%2F%3E%3CfeMergeNode%20in%3D%5C%22SourceGraphic%5C%22%20%2F%3E%3C%2FfeMerge%3E%3C%2Ffilter%3E%3C%2Fsvg%3E%23filter'); }", ""] + ], "?-url"); test("filter hash with url", ".highlight { filter: url(#highlight); }", [ [1, ".highlight { filter: url(#highlight); }", ""] diff --git a/test/valuesTest.js b/test/valuesTest.js index 57858407..5b77aa54 100644 --- a/test/valuesTest.js +++ b/test/valuesTest.js @@ -66,4 +66,55 @@ describe("values", function() { })() } ); + testLocal("should import values contain comma", + "@value color from './file1'; @value shadow: 0 0 color,0 0 color; .ghi { box-shadow: shadow; }", [ + [ 2, "", "" ], + [ 1, ".ghi { box-shadow: 0 0 red,0 0 red; }", "" ] + ], { + color: "red", + shadow: "0 0 red,0 0 red" + }, "", { + "./file1": (function() { + var a = [[2, "", ""]]; + a.locals = { + color: "red", + }; + return a; + })() + } + ); + testLocal("should import values contain comma and space before comma", + "@value color from './file1'; @value shadow: 0 0 color ,0 0 color; .ghi { box-shadow: shadow; }", [ + [ 2, "", "" ], + [ 1, ".ghi { box-shadow: 0 0 red ,0 0 red; }", "" ] + ], { + color: "red", + shadow: "0 0 red ,0 0 red" + }, "", { + "./file1": (function() { + var a = [[2, "", ""]]; + a.locals = { + color: "red", + }; + return a; + })() + } + ); + testLocal("should import values contain tralling comma and space after comma", + "@value color from './file1'; @value shadow: 0 0 color, 0 0 color; .ghi { box-shadow: shadow; }", [ + [ 2, "", "" ], + [ 1, ".ghi { box-shadow: 0 0 red, 0 0 red; }", "" ] + ], { + color: "red", + shadow: "0 0 red, 0 0 red" + }, "", { + "./file1": (function() { + var a = [[2, "", ""]]; + a.locals = { + color: "red", + }; + return a; + })() + } + ); });