UNPKG

6.95 kBMarkdownView Raw
1# postcss-import
2
3[![Build](https://img.shields.io/travis/postcss/postcss-import/master)](https://travis-ci.org/postcss/postcss-import)
4[![Version](https://img.shields.io/npm/v/postcss-import)](https://github.com/postcss/postcss-import/blob/master/CHANGELOG.md)
5[![postcss compatibility](https://img.shields.io/npm/dependency-version/postcss-import/peer/postcss)](https://postcss.org/)
6
7> [PostCSS](https://github.com/postcss/postcss) plugin to transform `@import`
8rules by inlining content.
9
10This plugin can consume local files, node modules or web_modules.
11To resolve path of an `@import` rule, it can look into root directory
12(by default `process.cwd()`), `web_modules`, `node_modules`
13or local modules.
14_When importing a module, it will look for `index.css` or file referenced in
15`package.json` in the `style` or `main` fields._
16You can also provide manually multiples paths where to look at.
17
18**Notes:**
19
20- **This plugin should probably be used as the first plugin of your list.
21This way, other plugins will work on the AST as if there were only a single file
22to process, and will probably work as you can expect**.
23- This plugin works great with
24[postcss-url](https://github.com/postcss/postcss-url) plugin,
25which will allow you to adjust assets `url()` (or even inline them) after
26inlining imported files.
27- In order to optimize output, **this plugin will only import a file once** on
28a given scope (root, media query...).
29Tests are made from the path & the content of imported files (using a hash
30table).
31If this behavior is not what you want, look at `skipDuplicates` option
32- If you are looking for **Glob Imports**, you can use [postcss-import-ext-glob](https://github.com/dimitrinicolas/postcss-import-ext-glob) to extend postcss-import.
33- Imports which are not modified (by `options.filter` or because they are remote
34 imports) are moved to the top of the output.
35- **This plugin attempts to follow the CSS `@import` spec**; `@import`
36 statements must precede all other statements (besides `@charset`).
37
38## Installation
39
40```console
41$ npm install -D postcss-import
42```
43
44## Usage
45
46Unless your stylesheet is in the same place where you run postcss
47(`process.cwd()`), you will need to use `from` option to make relative imports
48work.
49
50```js
51// dependencies
52const fs = require("fs")
53const postcss = require("postcss")
54const atImport = require("postcss-import")
55
56// css to be processed
57const css = fs.readFileSync("css/input.css", "utf8")
58
59// process css
60postcss()
61 .use(atImport())
62 .process(css, {
63 // `from` option is needed here
64 from: "css/input.css"
65 })
66 .then((result) => {
67 const output = result.css
68
69 console.log(output)
70 })
71```
72
73`css/input.css`:
74
75```css
76/* can consume `node_modules`, `web_modules` or local modules */
77@import "cssrecipes-defaults"; /* == @import "../node_modules/cssrecipes-defaults/index.css"; */
78@import "normalize.css"; /* == @import "../node_modules/normalize.css/normalize.css"; */
79
80@import "foo.css"; /* relative to css/ according to `from` option above */
81
82@import "bar.css" (min-width: 25em);
83
84@import 'baz.css' layer(baz-layer);
85
86body {
87 background: black;
88}
89```
90
91will give you:
92
93```css
94/* ... content of ../node_modules/cssrecipes-defaults/index.css */
95/* ... content of ../node_modules/normalize.css/normalize.css */
96
97/* ... content of css/foo.css */
98
99@media (min-width: 25em) {
100/* ... content of css/bar.css */
101}
102
103@layer baz-layer {
104/* ... content of css/baz.css */
105}
106
107body {
108 background: black;
109}
110```
111
112Checkout the [tests](test) for more examples.
113
114### Options
115
116### `filter`
117Type: `Function`
118Default: `() => true`
119
120Only transform imports for which the test function returns `true`. Imports for
121which the test function returns `false` will be left as is. The function gets
122the path to import as an argument and should return a boolean.
123
124#### `root`
125
126Type: `String`
127Default: `process.cwd()` or _dirname of
128[the postcss `from`](https://github.com/postcss/postcss#node-source)_
129
130Define the root where to resolve path (eg: place where `node_modules` are).
131Should not be used that much.
132_Note: nested `@import` will additionally benefit of the relative dirname of
133imported files._
134
135#### `path`
136
137Type: `String|Array`
138Default: `[]`
139
140A string or an array of paths in where to look for files.
141
142#### `plugins`
143
144Type: `Array`
145Default: `undefined`
146
147An array of plugins to be applied on each imported files.
148
149#### `resolve`
150
151Type: `Function`
152Default: `null`
153
154You can provide a custom path resolver with this option. This function gets
155`(id, basedir, importOptions)` arguments and should return a path, an array of
156paths or a promise resolving to the path(s). If you do not return an absolute
157path, your path will be resolved to an absolute path using the default
158resolver.
159You can use [resolve](https://github.com/substack/node-resolve) for this.
160
161#### `load`
162
163Type: `Function`
164Default: null
165
166You can overwrite the default loading way by setting this option.
167This function gets `(filename, importOptions)` arguments and returns content or
168promised content.
169
170#### `skipDuplicates`
171
172Type: `Boolean`
173Default: `true`
174
175By default, similar files (based on the same content) are being skipped.
176It's to optimize output and skip similar files like `normalize.css` for example.
177If this behavior is not what you want, just set this option to `false` to
178disable it.
179
180#### `addModulesDirectories`
181
182Type: `Array`
183Default: `[]`
184
185An array of folder names to add to [Node's resolver](https://github.com/substack/node-resolve).
186Values will be appended to the default resolve directories:
187`["node_modules", "web_modules"]`.
188
189This option is only for adding additional directories to default resolver. If
190you provide your own resolver via the `resolve` configuration option above, then
191this value will be ignored.
192
193#### `nameLayer`
194
195Type: `Function`
196Default: `null`
197
198You can provide a custom naming function for anonymous layers (`@import 'baz.css' layer;`).
199This function gets `(index, rootFilename)` arguments and should return a unique string.
200
201This option only influences imports without a layer name.
202Without this option the plugin will warn on anonymous layers.
203
204#### Example with some options
205
206```js
207const postcss = require("postcss")
208const atImport = require("postcss-import")
209
210postcss()
211 .use(atImport({
212 path: ["src/css"],
213 }))
214 .process(cssString)
215 .then((result) => {
216 const { css } = result
217 })
218```
219
220## `dependency` Message Support
221
222`postcss-import` adds a message to `result.messages` for each `@import`. Messages are in the following format:
223
224```
225{
226 type: 'dependency',
227 file: absoluteFilePath,
228 parent: fileContainingTheImport
229}
230```
231
232This is mainly for use by postcss runners that implement file watching.
233
234---
235
236## CONTRIBUTING
237
238* ⇄ Pull requests and ★ Stars are always welcome.
239* For bugs and feature requests, please create an issue.
240* Pull requests must be accompanied by passing automated tests (`$ npm test`).
241
242## [Changelog](CHANGELOG.md)
243
244## [License](LICENSE)