1133d3e1c1a65def67353015f94b3abe47712cb9b568ad601d077ba430410318b679cc921eba4a69972c2f0431db527da5a28761e250640d25daebabadfd16 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. [![npm][npm]][npm-url]
  2. [![node][node]][node-url]
  3. [![deps][deps]][deps-url]
  4. [![tests][tests]][tests-url]
  5. [![coverage][cover]][cover-url]
  6. [![chat][chat]][chat-url]
  7. <div align="center">
  8. <img width="180" height="180" vspace="20"
  9. src="https://cdn.worldvectorlogo.com/logos/css-3.svg">
  10. <a href="https://github.com/webpack/webpack">
  11. <img width="200" height="200"
  12. src="https://webpack.js.org/assets/icon-square-big.svg">
  13. </a>
  14. <h1>CSS Loader</h1>
  15. </div>
  16. <h2 align="center">Install</h2>
  17. ```bash
  18. npm install --save-dev css-loader
  19. ```
  20. <h2 align="center">Usage</h2>
  21. The `css-loader` interprets `@import` and `url()` like `import/require()`
  22. and will resolve them.
  23. Good loaders for requiring your assets are the [file-loader](https://github.com/webpack/file-loader)
  24. and the [url-loader](https://github.com/webpack/url-loader) which you should specify in your config (see [below](https://github.com/webpack-contrib/css-loader#assets)).
  25. **file.js**
  26. ```js
  27. import css from 'file.css';
  28. ```
  29. **webpack.config.js**
  30. ```js
  31. module.exports = {
  32. module: {
  33. rules: [
  34. {
  35. test: /\.css$/,
  36. use: [ 'style-loader', 'css-loader' ]
  37. }
  38. ]
  39. }
  40. }
  41. ```
  42. ### `toString`
  43. You can also use the css-loader results directly as string, such as in Angular's component style.
  44. **webpack.config.js**
  45. ```js
  46. {
  47.    test: /\.css$/,
  48.    use: [
  49.      'to-string-loader',
  50. 'css-loader'
  51.    ]
  52. }
  53. ```
  54. or
  55. ```js
  56. const css = require('./test.css').toString();
  57. console.log(css); // {String}
  58. ```
  59. If there are SourceMaps, they will also be included in the result string.
  60. If, for one reason or another, you need to extract CSS as a
  61. plain string resource (i.e. not wrapped in a JS module) you
  62. might want to check out the [extract-loader](https://github.com/peerigon/extract-loader).
  63. It's useful when you, for instance, need to post process the CSS as a string.
  64. **webpack.config.js**
  65. ```js
  66. {
  67.    test: /\.css$/,
  68.    use: [
  69. 'handlebars-loader', // handlebars loader expects raw resource string
  70.      'extract-loader',
  71. 'css-loader'
  72.    ]
  73. }
  74. ```
  75. <h2 align="center">Options</h2>
  76. |Name|Type|Default|Description|
  77. |:--:|:--:|:-----:|:----------|
  78. |**[`root`](#root)**|`{String}`|`/`|Path to resolve URLs, URLs starting with `/` will not be translated|
  79. |**[`url`](#url)**|`{Boolean}`|`true`| Enable/Disable `url()` handling|
  80. |**[`alias`](#alias)**|`{Object}`|`{}`|Create aliases to import certain modules more easily|
  81. |**[`import`](#import)** |`{Boolean}`|`true`| Enable/Disable @import handling|
  82. |**[`modules`](#modules)**|`{Boolean}`|`false`|Enable/Disable CSS Modules|
  83. |**[`minimize`](#minimize)**|`{Boolean\|Object}`|`false`|Enable/Disable minification|
  84. |**[`sourceMap`](#sourcemap)**|`{Boolean}`|`false`|Enable/Disable Sourcemaps|
  85. |**[`camelCase`](#camelcase)**|`{Boolean\|String}`|`false`|Export Classnames in CamelCase|
  86. |**[`importLoaders`](#importloaders)**|`{Number}`|`0`|Number of loaders applied before CSS loader|
  87. |**`localIdentName`**|`{String}`|`[hash:base64]`|Configure the generated ident|
  88. ### `root`
  89. For URLs that start with a `/`, the default behavior is to not translate them.
  90. `url(/image.png) => url(/image.png)`
  91. If a `root` query parameter is set, however, it will be prepended to the URL
  92. and then translated.
  93. **webpack.config.js**
  94. ```js
  95. {
  96. loader: 'css-loader',
  97. options: { root: '.' }
  98. }
  99. ```
  100. `url(/image.png)` => `require('./image.png')`
  101. Using 'Root-relative' urls is not recommended. You should only use it for legacy CSS files.
  102. ### `url`
  103. To disable `url()` resolving by `css-loader` set the option to `false`.
  104. To be compatible with existing css files (if not in CSS Module mode).
  105. ```
  106. url(image.png) => require('./image.png')
  107. url(~module/image.png) => require('module/image.png')
  108. ```
  109. ### `alias`
  110. 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.).
  111. `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)
  112. **file.scss**
  113. ```css
  114. @charset "UTF-8";
  115. @import "bootstrap";
  116. ```
  117. **webpack.config.js**
  118. ```js
  119. {
  120. test: /\.scss$/,
  121. use: [
  122. {
  123. loader: "style-loader"
  124. },
  125. {
  126. loader: "css-loader",
  127. options: {
  128. alias: {
  129. "../fonts/bootstrap": "bootstrap-sass/assets/fonts/bootstrap"
  130. }
  131. }
  132. },
  133. {
  134. loader: "sass-loader",
  135. options: {
  136. includePaths: [
  137. path.resolve("./node_modules/bootstrap-sass/assets/stylesheets")
  138. ]
  139. }
  140. }
  141. ]
  142. }
  143. ```
  144. Check out this [working bootstrap example](https://github.com/bbtfr/webpack2-bootstrap-sass-sample).
  145. ### `import`
  146. To disable `@import` resolving by `css-loader` set the option to `false`
  147. ```css
  148. @import url('https://fonts.googleapis.com/css?family=Roboto');
  149. ```
  150. > _⚠️ Use with caution, since this disables resolving for **all** `@import`s, including css modules `composes: xxx from 'path/to/file.css'` feature._
  151. ### [`modules`](https://github.com/css-modules/css-modules)
  152. The query parameter `modules` enables the **CSS Modules** spec.
  153. This enables local scoped CSS by default. (You can switch it off with `:global(...)` or `:global` for selectors and/or rules.).
  154. #### `Scope`
  155. By default CSS exports all classnames into a global selector scope. Styles can be locally scoped to avoid globally scoping styles.
  156. The syntax `:local(.className)` can be used to declare `className` in the local scope. The local identifiers are exported by the module.
  157. With `:local` (without brackets) local mode can be switched on for this selector. `:global(.className)` can be used to declare an explicit global selector. With `:global` (without brackets) global mode can be switched on for this selector.
  158. The loader replaces local selectors with unique identifiers. The choosen unique identifiers are exported by the module.
  159. ```css
  160. :local(.className) { background: red; }
  161. :local .className { color: green; }
  162. :local(.className .subClass) { color: green; }
  163. :local .className .subClass :global(.global-class-name) { color: blue; }
  164. ```
  165. ```css
  166. ._23_aKvs-b8bW2Vg3fwHozO { background: red; }
  167. ._23_aKvs-b8bW2Vg3fwHozO { color: green; }
  168. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 { color: green; }
  169. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name { color: blue; }
  170. ```
  171. > :information_source: Identifiers are exported
  172. ```js
  173. exports.locals = {
  174. className: '_23_aKvs-b8bW2Vg3fwHozO',
  175. subClass: '_13LGdX8RMStbBE9w-t0gZ1'
  176. }
  177. ```
  178. CamelCase is recommended for local selectors. They are easier to use in the within the imported JS module.
  179. `url()` URLs in block scoped (`:local .abc`) rules behave like requests in modules.
  180. ```
  181. file.png => ./file.png
  182. ~module/file.png => module/file.png
  183. ```
  184. You can use `:local(#someId)`, but this is not recommended. Use classes instead of ids.
  185. You can configure the generated ident with the `localIdentName` query parameter (default `[hash:base64]`).
  186. **webpack.config.js**
  187. ```js
  188. {
  189. test: /\.css$/,
  190. use: [
  191. {
  192. loader: 'css-loader',
  193. options: {
  194. modules: true,
  195. localIdentName: '[path][name]__[local]--[hash:base64:5]'
  196. }
  197. }
  198. ]
  199. }
  200. ```
  201. 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).
  202. **webpack.config.js**
  203. ```js
  204. {
  205. loader: 'css-loader',
  206. options: {
  207. modules: true,
  208. localIdentName: '[path][name]__[local]--[hash:base64:5]',
  209. getLocalIdent: (context, localIdentName, localName, options) => {
  210. return 'whatever_random_class_name'
  211. }
  212. }
  213. }
  214. ```
  215. > :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.
  216. #### `Composing`
  217. When declaring a local classname you can compose a local class from another local classname.
  218. ```css
  219. :local(.className) {
  220. background: red;
  221. color: yellow;
  222. }
  223. :local(.subClass) {
  224. composes: className;
  225. background: blue;
  226. }
  227. ```
  228. This doesn't result in any change to the CSS itself but exports multiple classnames.
  229. ```js
  230. exports.locals = {
  231. className: '_23_aKvs-b8bW2Vg3fwHozO',
  232. subClass: '_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO'
  233. }
  234. ```
  235. ``` css
  236. ._23_aKvs-b8bW2Vg3fwHozO {
  237. background: red;
  238. color: yellow;
  239. }
  240. ._13LGdX8RMStbBE9w-t0gZ1 {
  241. background: blue;
  242. }
  243. ```
  244. #### `Importing`
  245. To import a local classname from another module.
  246. ```css
  247. :local(.continueButton) {
  248. composes: button from 'library/button.css';
  249. background: red;
  250. }
  251. ```
  252. ```css
  253. :local(.nameEdit) {
  254. composes: edit highlight from './edit.css';
  255. background: red;
  256. }
  257. ```
  258. To import from multiple modules use multiple `composes:` rules.
  259. ```css
  260. :local(.className) {
  261. composes: edit hightlight from './edit.css';
  262. composes: button from 'module/button.css';
  263. composes: classFromThisModule;
  264. background: red;
  265. }
  266. ```
  267. ### `minimize`
  268. By default the css-loader minimizes the css if specified by the module system.
  269. In some cases the minification is destructive to the css, so you can provide your own options to the cssnano-based minifier if needed. See [cssnano's documentation](http://cssnano.co/guides/) for more information on the available options.
  270. You can also disable or enforce minification with the `minimize` query parameter.
  271. **webpack.config.js**
  272. ```js
  273. {
  274. loader: 'css-loader',
  275. options: {
  276. minimize: true || {/* CSSNano Options */}
  277. }
  278. }
  279. ```
  280. ### `sourceMap`
  281. To include source maps set the `sourceMap` option.
  282. I. e. the extract-text-webpack-plugin can handle them.
  283. 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.
  284. **webpack.config.js**
  285. ```js
  286. {
  287. loader: 'css-loader',
  288. options: {
  289. sourceMap: true
  290. }
  291. }
  292. ```
  293. ### `camelCase`
  294. 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.
  295. |Name|Type|Description|
  296. |:--:|:--:|:----------|
  297. |**`true`**|`{Boolean}`|Class names will be camelized|
  298. |**`'dashes'`**|`{String}`|Only dashes in class names will be camelized|
  299. |**`'only'`** |`{String}`|Introduced in `0.27.1`. Class names will be camelized, the original class name will be removed from the locals|
  300. |**`'dashesOnly'`**|`{String}`|Introduced in `0.27.1`. Dashes in class names will be camelized, the original class name will be removed from the locals|
  301. **file.css**
  302. ```css
  303. .class-name {}
  304. ```
  305. **file.js**
  306. ```js
  307. import { className } from 'file.css';
  308. ```
  309. **webpack.config.js**
  310. ```js
  311. {
  312. loader: 'css-loader',
  313. options: {
  314. camelCase: true
  315. }
  316. }
  317. ```
  318. ### `importLoaders`
  319. The query parameter `importLoaders` allows to configure how many loaders before `css-loader` should be applied to `@import`ed resources.
  320. **webpack.config.js**
  321. ```js
  322. {
  323. test: /\.css$/,
  324. use: [
  325. 'style-loader',
  326. {
  327. loader: 'css-loader',
  328. options: {
  329. importLoaders: 2 // 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader
  330. }
  331. },
  332. 'postcss-loader',
  333. 'sass-loader'
  334. ]
  335. }
  336. ```
  337. This may change in the future, when the module system (i. e. webpack) supports loader matching by origin.
  338. <h2 align="center">Examples</h2>
  339. ### Assets
  340. 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.
  341. **webpack.config.js**
  342. ```js
  343. module.exports = {
  344. module: {
  345. rules: [
  346. {
  347. test: /\.css$/,
  348. use: [ 'style-loader', 'css-loader' ]
  349. },
  350. {
  351. test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
  352. loader: 'url-loader',
  353. options: {
  354. limit: 10000
  355. }
  356. }
  357. ]
  358. }
  359. }
  360. ```
  361. ### Extract
  362. 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.
  363. **webpack.config.js**
  364. ```js
  365. const env = process.env.NODE_ENV
  366. const ExtractTextPlugin = require('extract-text-webpack-plugin')
  367. module.exports = {
  368. module: {
  369. rules: [
  370. {
  371. test: /\.css$/,
  372. use: env === 'production'
  373. ? ExtractTextPlugin.extract({
  374. fallback: 'style-loader',
  375. use: [ 'css-loader' ]
  376. })
  377. : [ 'style-loader', 'css-loader' ]
  378. },
  379. ]
  380. },
  381. plugins: env === 'production'
  382. ? [
  383. new ExtractTextPlugin({
  384. filename: '[name].css'
  385. })
  386. ]
  387. : []
  388. }
  389. ```
  390. <h2 align="center">Maintainers</h2>
  391. <table>
  392. <tbody>
  393. <tr>
  394. <td align="center">
  395. <img width="150" height="150"
  396. src="https://github.com/bebraw.png?v=3&s=150">
  397. </br>
  398. <a href="https://github.com/bebraw">Juho Vepsäläinen</a>
  399. </td>
  400. <td align="center">
  401. <img width="150" height="150"
  402. src="https://github.com/d3viant0ne.png?v=3&s=150">
  403. </br>
  404. <a href="https://github.com/d3viant0ne">Joshua Wiens</a>
  405. </td>
  406. <td align="center">
  407. <img width="150" height="150"
  408. src="https://github.com/SpaceK33z.png?v=3&s=150">
  409. </br>
  410. <a href="https://github.com/SpaceK33z">Kees Kluskens</a>
  411. </td>
  412. <td align="center">
  413. <img width="150" height="150"
  414. src="https://github.com/TheLarkInn.png?v=3&s=150">
  415. </br>
  416. <a href="https://github.com/TheLarkInn">Sean Larkin</a>
  417. </td>
  418. </tr>
  419. <tr>
  420. <td align="center">
  421. <img width="150" height="150"
  422. src="https://github.com/michael-ciniawsky.png?v=3&s=150">
  423. </br>
  424. <a href="https://github.com/michael-ciniawsky">Michael Ciniawsky</a>
  425. </td>
  426. <td align="center">
  427. <img width="150" height="150"
  428. src="https://github.com/evilebottnawi.png?v=3&s=150">
  429. </br>
  430. <a href="https://github.com/evilebottnawi">Evilebot Tnawi</a>
  431. </td>
  432. <td align="center">
  433. <img width="150" height="150"
  434. src="https://github.com/joscha.png?v=3&s=150">
  435. </br>
  436. <a href="https://github.com/joscha">Joscha Feth</a>
  437. </td>
  438. </tr>
  439. <tbody>
  440. </table>
  441. [npm]: https://img.shields.io/npm/v/css-loader.svg
  442. [npm-url]: https://npmjs.com/package/css-loader
  443. [node]: https://img.shields.io/node/v/css-loader.svg
  444. [node-url]: https://nodejs.org
  445. [deps]: https://david-dm.org/webpack-contrib/css-loader.svg
  446. [deps-url]: https://david-dm.org/webpack-contrib/css-loader
  447. [tests]: http://img.shields.io/travis/webpack-contrib/css-loader.svg
  448. [tests-url]: https://travis-ci.org/webpack-contrib/css-loader
  449. [cover]: https://codecov.io/gh/webpack-contrib/css-loader/branch/master/graph/badge.svg
  450. [cover-url]: https://codecov.io/gh/webpack-contrib/css-loader
  451. [chat]: https://badges.gitter.im/webpack/webpack.svg
  452. [chat-url]: https://gitter.im/webpack/webpack