You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

454 lines
12 KiB

4 years ago
  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 a 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. |**[`url`](#url)**|`{Boolean}`|`true`| Enable/Disable `url()` handling|
  79. |**[`import`](#import)** |`{Boolean}`|`true`| Enable/Disable @import handling|
  80. |**[`modules`](#modules)**|`{Boolean}`|`false`|Enable/Disable CSS Modules|
  81. |**[`localIdentName`](#localidentname)**|`{String}`|`[hash:base64]`|Configure the generated ident|
  82. |**[`sourceMap`](#sourcemap)**|`{Boolean}`|`false`|Enable/Disable Sourcemaps|
  83. |**[`camelCase`](#camelcase)**|`{Boolean\|String}`|`false`|Export Classnames in CamelCase|
  84. |**[`importLoaders`](#importloaders)**|`{Number}`|`0`|Number of loaders applied before CSS loader|
  85. ### `url`
  86. To disable `url()` resolving by `css-loader` set the option to `false`.
  87. To be compatible with existing css files (if not in CSS Module mode).
  88. ```
  89. url(image.png) => require('./image.png')
  90. url(~module/image.png) => require('module/image.png')
  91. ```
  92. ### `import`
  93. To disable `@import` resolving by `css-loader` set the option to `false`
  94. ```css
  95. @import url('https://fonts.googleapis.com/css?family=Roboto');
  96. ```
  97. > _⚠️ Use with caution, since this disables resolving for **all** `@import`s, including css modules `composes: xxx from 'path/to/file.css'` feature._
  98. ### [`modules`](https://github.com/css-modules/css-modules)
  99. The query parameter `modules` enables the **CSS Modules** spec.
  100. This enables local scoped CSS by default. (You can switch it off with `:global(...)` or `:global` for selectors and/or rules.).
  101. #### `Scope`
  102. By default CSS exports all classnames into a global selector scope. Styles can be locally scoped to avoid globally scoping styles.
  103. The syntax `:local(.className)` can be used to declare `className` in the local scope. The local identifiers are exported by the module.
  104. 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.
  105. The loader replaces local selectors with unique identifiers. The chosen unique identifiers are exported by the module.
  106. ```css
  107. :local(.className) { background: red; }
  108. :local .className { color: green; }
  109. :local(.className .subClass) { color: green; }
  110. :local .className .subClass :global(.global-class-name) { color: blue; }
  111. ```
  112. ```css
  113. ._23_aKvs-b8bW2Vg3fwHozO { background: red; }
  114. ._23_aKvs-b8bW2Vg3fwHozO { color: green; }
  115. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 { color: green; }
  116. ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name { color: blue; }
  117. ```
  118. > ℹ️ Identifiers are exported
  119. ```js
  120. exports.locals = {
  121. className: '_23_aKvs-b8bW2Vg3fwHozO',
  122. subClass: '_13LGdX8RMStbBE9w-t0gZ1'
  123. }
  124. ```
  125. CamelCase is recommended for local selectors. They are easier to use within the imported JS module.
  126. `url()` URLs in block scoped (`:local .abc`) rules behave like requests in modules.
  127. ```
  128. file.png => ./file.png
  129. ~module/file.png => module/file.png
  130. ```
  131. You can use `:local(#someId)`, but this is not recommended. Use classes instead of ids.
  132. #### `Composing`
  133. When declaring a local classname you can compose a local class from another local classname.
  134. ```css
  135. :local(.className) {
  136. background: red;
  137. color: yellow;
  138. }
  139. :local(.subClass) {
  140. composes: className;
  141. background: blue;
  142. }
  143. ```
  144. This doesn't result in any change to the CSS itself but exports multiple classnames.
  145. ```js
  146. exports.locals = {
  147. className: '_23_aKvs-b8bW2Vg3fwHozO',
  148. subClass: '_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO'
  149. }
  150. ```
  151. ``` css
  152. ._23_aKvs-b8bW2Vg3fwHozO {
  153. background: red;
  154. color: yellow;
  155. }
  156. ._13LGdX8RMStbBE9w-t0gZ1 {
  157. background: blue;
  158. }
  159. ```
  160. #### `Importing`
  161. To import a local classname from another module.
  162. ```css
  163. :local(.continueButton) {
  164. composes: button from 'library/button.css';
  165. background: red;
  166. }
  167. ```
  168. ```css
  169. :local(.nameEdit) {
  170. composes: edit highlight from './edit.css';
  171. background: red;
  172. }
  173. ```
  174. To import from multiple modules use multiple `composes:` rules.
  175. ```css
  176. :local(.className) {
  177. composes: edit hightlight from './edit.css';
  178. composes: button from 'module/button.css';
  179. composes: classFromThisModule;
  180. background: red;
  181. }
  182. ```
  183. ### `localIdentName`
  184. You can configure the generated ident with the `localIdentName` query parameter. See [loader-utils's documentation](https://github.com/webpack/loader-utils#interpolatename) for more information on options.
  185. **webpack.config.js**
  186. ```js
  187. {
  188. test: /\.css$/,
  189. use: [
  190. {
  191. loader: 'css-loader',
  192. options: {
  193. modules: true,
  194. localIdentName: '[path][name]__[local]--[hash:base64:5]'
  195. }
  196. }
  197. ]
  198. }
  199. ```
  200. 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).
  201. **webpack.config.js**
  202. ```js
  203. {
  204. loader: 'css-loader',
  205. options: {
  206. modules: true,
  207. localIdentName: '[path][name]__[local]--[hash:base64:5]',
  208. getLocalIdent: (context, localIdentName, localName, options) => {
  209. return 'whatever_random_class_name'
  210. }
  211. }
  212. }
  213. ```
  214. > ℹ️ 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.
  215. ### `sourceMap`
  216. To include source maps set the `sourceMap` option.
  217. I.e. the extract-text-webpack-plugin can handle them.
  218. 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 includes the server URL.
  219. **webpack.config.js**
  220. ```js
  221. {
  222. loader: 'css-loader',
  223. options: {
  224. sourceMap: true
  225. }
  226. }
  227. ```
  228. ### `camelCase`
  229. 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.
  230. |Name|Type|Description|
  231. |:--:|:--:|:----------|
  232. |**`true`**|`{Boolean}`|Class names will be camelized|
  233. |**`'dashes'`**|`{String}`|Only dashes in class names will be camelized|
  234. |**`'only'`** |`{String}`|Introduced in `0.27.1`. Class names will be camelized, the original class name will be removed from the locals|
  235. |**`'dashesOnly'`**|`{String}`|Introduced in `0.27.1`. Dashes in class names will be camelized, the original class name will be removed from the locals|
  236. **file.css**
  237. ```css
  238. .class-name {}
  239. ```
  240. **file.js**
  241. ```js
  242. import { className } from 'file.css';
  243. ```
  244. **webpack.config.js**
  245. ```js
  246. {
  247. loader: 'css-loader',
  248. options: {
  249. camelCase: true
  250. }
  251. }
  252. ```
  253. ### `importLoaders`
  254. The query parameter `importLoaders` allows you to configure how many loaders before `css-loader` should be applied to `@import`ed resources.
  255. **webpack.config.js**
  256. ```js
  257. {
  258. test: /\.css$/,
  259. use: [
  260. 'style-loader',
  261. {
  262. loader: 'css-loader',
  263. options: {
  264. importLoaders: 2 // 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader
  265. }
  266. },
  267. 'postcss-loader',
  268. 'sass-loader'
  269. ]
  270. }
  271. ```
  272. This may change in the future when the module system (i. e. webpack) supports loader matching by origin.
  273. <h2 align="center">Examples</h2>
  274. ### Assets
  275. 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.
  276. **webpack.config.js**
  277. ```js
  278. module.exports = {
  279. module: {
  280. rules: [
  281. {
  282. test: /\.css$/,
  283. use: [ 'style-loader', 'css-loader' ]
  284. },
  285. {
  286. test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
  287. loader: 'url-loader',
  288. options: {
  289. limit: 10000
  290. }
  291. }
  292. ]
  293. }
  294. }
  295. ```
  296. ### Extract
  297. 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.
  298. This can be achieved by using the [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin) to extract the CSS when running in production mode.
  299. <h2 align="center">Maintainers</h2>
  300. <table>
  301. <tbody>
  302. <tr>
  303. <td align="center">
  304. <img width="150" height="150"
  305. src="https://github.com/bebraw.png?v=3&s=150">
  306. </br>
  307. <a href="https://github.com/bebraw">Juho Vepsäläinen</a>
  308. </td>
  309. <td align="center">
  310. <img width="150" height="150"
  311. src="https://github.com/d3viant0ne.png?v=3&s=150">
  312. </br>
  313. <a href="https://github.com/d3viant0ne">Joshua Wiens</a>
  314. </td>
  315. <td align="center">
  316. <img width="150" height="150"
  317. src="https://github.com/SpaceK33z.png?v=3&s=150">
  318. </br>
  319. <a href="https://github.com/SpaceK33z">Kees Kluskens</a>
  320. </td>
  321. <td align="center">
  322. <img width="150" height="150"
  323. src="https://github.com/TheLarkInn.png?v=3&s=150">
  324. </br>
  325. <a href="https://github.com/TheLarkInn">Sean Larkin</a>
  326. </td>
  327. </tr>
  328. <tr>
  329. <td align="center">
  330. <img width="150" height="150"
  331. src="https://github.com/michael-ciniawsky.png?v=3&s=150">
  332. </br>
  333. <a href="https://github.com/michael-ciniawsky">Michael Ciniawsky</a>
  334. </td>
  335. <td align="center">
  336. <img width="150" height="150"
  337. src="https://github.com/evilebottnawi.png?v=3&s=150">
  338. </br>
  339. <a href="https://github.com/evilebottnawi">Evilebot Tnawi</a>
  340. </td>
  341. <td align="center">
  342. <img width="150" height="150"
  343. src="https://github.com/joscha.png?v=3&s=150">
  344. </br>
  345. <a href="https://github.com/joscha">Joscha Feth</a>
  346. </td>
  347. </tr>
  348. <tbody>
  349. </table>
  350. [npm]: https://img.shields.io/npm/v/css-loader.svg
  351. [npm-url]: https://npmjs.com/package/css-loader
  352. [node]: https://img.shields.io/node/v/css-loader.svg
  353. [node-url]: https://nodejs.org
  354. [deps]: https://david-dm.org/webpack-contrib/css-loader.svg
  355. [deps-url]: https://david-dm.org/webpack-contrib/css-loader
  356. [tests]: http://img.shields.io/travis/webpack-contrib/css-loader.svg
  357. [tests-url]: https://travis-ci.org/webpack-contrib/css-loader
  358. [cover]: https://codecov.io/gh/webpack-contrib/css-loader/branch/master/graph/badge.svg
  359. [cover-url]: https://codecov.io/gh/webpack-contrib/css-loader
  360. [chat]: https://badges.gitter.im/webpack/webpack.svg
  361. [chat-url]: https://gitter.im/webpack/webpack