Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

postcss-import

postcss42.3mMIT16.1.0TypeScript support: definitely-typed

PostCSS plugin to import CSS files

css, postcss, postcss-plugin, import, node modules, npm

readme

postcss-import

Build Version postcss compatibility

PostCSS plugin to transform @import rules by inlining content.

This plugin can consume local files, node modules or web_modules. To resolve path of an @import rule, it can look into root directory (by default process.cwd()), web_modules, node_modules or local modules. When importing a module, it will look for index.css or file referenced in package.json in the style or main fields. You can also provide manually multiples paths where to look at.

Notes:

  • This plugin should probably be used as the first plugin of your list. This way, other plugins will work on the AST as if there were only a single file to process, and will probably work as you can expect.
  • Running postcss-url after postcss-import in your plugin chain will allow you to adjust assets url() (or even inline them) after inlining imported files.
  • In order to optimize output, this plugin will only import a file once on a given scope (root, media query...). Tests are made from the path & the content of imported files (using a hash table). If this behavior is not what you want, look at skipDuplicates option
  • If you are looking for Glob Imports, you can use postcss-import-ext-glob to extend postcss-import.
  • If you want to import remote sources, you can use postcss-import-url with its dataUrls plugin option to extend postcss-import.
  • Imports which are not modified (by options.filter or because they are remote imports) are moved to the top of the output.
  • This plugin attempts to follow the CSS @import spec; @import statements must precede all other statements (besides @charset).

Installation

$ npm install -D postcss-import

Usage

Unless your stylesheet is in the same place where you run postcss (process.cwd()), you will need to use from option to make relative imports work.

// dependencies
const fs = require("fs")
const postcss = require("postcss")
const atImport = require("postcss-import")

// css to be processed
const css = fs.readFileSync("css/input.css", "utf8")

// process css
postcss()
  .use(atImport())
  .process(css, {
    // `from` option is needed here
    from: "css/input.css"
  })
  .then((result) => {
    const output = result.css

    console.log(output)
  })

css/input.css:

/* remote urls are preserved */
@import "https://example.com/styles.css";

/* can consume `node_modules`, `web_modules` or local modules */
@import "cssrecipes-defaults"; /* == @import "../node_modules/cssrecipes-defaults/index.css"; */
@import "normalize.css"; /* == @import "../node_modules/normalize.css/normalize.css"; */

@import "foo.css"; /* relative to css/ according to `from` option above */

/* all standard notations of the "url" value are supported */
@import url(foo-1.css);
@import url("foo-2.css");

@import "bar.css" (min-width: 25em);

@import 'baz.css' layer(baz-layer);

body {
  background: black;
}

will give you:

@import "https://example.com/styles.css";

/* ... content of ../node_modules/cssrecipes-defaults/index.css */
/* ... content of ../node_modules/normalize.css/normalize.css */

/* ... content of css/foo.css */

/* ... content of css/foo-1.css */
/* ... content of css/foo-2.css */

@media (min-width: 25em) {
/* ... content of css/bar.css */
}

@layer baz-layer {
/* ... content of css/baz.css */
}

body {
  background: black;
}

Checkout the tests for more examples.

Options

filter

Type: Function
Default: () => true

Only transform imports for which the test function returns true. Imports for which the test function returns false will be left as is. The function gets the path to import as an argument and should return a boolean.

root

Type: String
Default: process.cwd() or dirname of the postcss from

Define the root where to resolve path (eg: place where node_modules are). Should not be used that much.
Note: nested @import will additionally benefit of the relative dirname of imported files.

path

Type: String|Array
Default: []

A string or an array of paths in where to look for files.

plugins

Type: Array
Default: undefined

An array of plugins to be applied on each imported files.

resolve

Type: Function
Default: null

You can provide a custom path resolver with this option. This function gets (id, basedir, importOptions, astNode) arguments and should return a path, an array of paths or a promise resolving to the path(s). If you do not return an absolute path, your path will be resolved to an absolute path using the default resolver. You can use resolve for this.

load

Type: Function
Default: null

You can overwrite the default loading way by setting this option. This function gets (filename, importOptions) arguments and returns content or promised content.

skipDuplicates

Type: Boolean
Default: true

By default, similar files (based on the same content) are being skipped. It's to optimize output and skip similar files like normalize.css for example. If this behavior is not what you want, just set this option to false to disable it.

addModulesDirectories

Type: Array
Default: []

An array of folder names to add to Node's resolver. Values will be appended to the default resolve directories: ["node_modules", "web_modules"].

This option is only for adding additional directories to default resolver. If you provide your own resolver via the resolve configuration option above, then this value will be ignored.

warnOnEmpty

Type: Boolean
Default: true

By default postcss-import warns when an empty file is imported.
Set this option to false to disable this warning.

Example with some options

const postcss = require("postcss")
const atImport = require("postcss-import")

postcss()
  .use(atImport({
    path: ["src/css"],
  }))
  .process(cssString)
  .then((result) => {
    const { css } = result
  })

dependency Message Support

postcss-import adds a message to result.messages for each @import. Messages are in the following format:

{
  type: 'dependency',
  file: absoluteFilePath,
  parent: fileContainingTheImport
}

This is mainly for use by postcss runners that implement file watching.


CONTRIBUTING

  • ⇄ Pull requests and ★ Stars are always welcome.
  • For bugs and feature requests, please create an issue.
  • Pull requests must be accompanied by passing automated tests ($ npm test).

Changelog

License

changelog

16.1.0 / 2024-03-20

  • Allow bundling URLs with fragments (useful for Vite users) (#560, #561)

16.0.1 / 2024-02-14

  • Fix crash when handling some @imports with media conditions (#557, #558)

16.0.0 / 2024-01-02

  • BREAKING: Require Node.js v18+ (#550, #551)
  • BREAKING: Signifigant rewrite, with small behavioral tweaks in a number of edge cases
  • Support for @supports conditional imports added (#532, #548)
  • When skipDuplicates is false, handles import cycles correctly (#462, #535)
  • Add warnOnEmpty option to allow disabling warnings for empty files (#84, #541)
  • Use proper node.errors (#518, #540)

Huge thanks to @romainmenke for all the hard work he put into this release.

15.1.0 / 2022-12-07

  • Add data: URL support (this is not useful for most consumers) (#515)

15.0.1 / 2022-12-01

  • Preserve layer in ignored @imports (#510, #511)
  • Join media queries in the correct order (#512, #513)

15.0.0 / 2022-08-30

  • BREAKING: Require Node.js v14+ (#497)
  • BREAKING: Require nameLayer option for handling anonymous layers (#496)
  • Fix handling of @media queries inside layered imports (#495, #496)

14.1.0 / 2022-03-22

  • Add @layer support (#483)

14.0.2 / 2021-05-10

  • Remove remaining direct import of postcss package (#455, #456)

14.0.1 / 2021-03-31

  • Fix bug with @charset statements in media imports (#448, #453)

14.0.0 / 2020-12-14

This release should not have breaking changes for the vast majority of users; only those with @charset statements in their CSS may be affected.

  • BREAKING: Error if multiple incompatible @charset statements (#447)
  • BREAKING: Warn if @charset statements are not at the top of files (#447)
  • Fix handing of @charset (#436, #447)

13.0.0 / 2020-10-20

  • BREAKING: Require Node 10+ (#429)
  • BREAKING: Upgrade to postcss v8 and require it as a peerDependency (#427, #432)
  • Update dependencies

12.0.1 / 2018-10-22

  • Add plugin property to dependency messages (#379, #380)

12.0.0 - 2018-08-04

11.1.0 - 2018-02-10

  • Added: filter option

11.0.0 - 2017-09-16

  • Changed: A syntax error in an imported file now throws an error instead of just warning (#264)
  • Changed: Symlink handling to be consistent with Node.js require (#300)

10.0.0 - 2017-05-12

  • Removed: Support for Node.js versions less than 4.5.x (#283)
  • Changed: Upgraded to Postcss v6 (#283)
  • Removed: jspm support (#283)
  • Removed: deprecated addDependencyTo option
  • Removed: onImport option
  • Changed: Doesn't depend on promise-each (#281)

9.1.0 - 2017-01-10

  • Added: addModulesDirectories option (#256)

9.0.0 - 2016-12-02

  • Removed: transform option (#250)
  • Removed: pkg-resolve is no longer a dependency; this should fix some issues with webpack. jspm users must manually install pkg-resolve if they want to load jspm modules (see https://github.com/postcss/postcss-import#jspm-usage for more info) (#243)
  • Changed: If a file is not found, it will now throw an error instead of just raising a warning (#247)
  • Changed: If a custom resolver does not return an absolute path, the default resolver will be applied to the returned path. (#249)
  • Changed: postcss-import will try to guess the correct parser for imported files, based on the file extension. (#245)
  • Changed: Deprecated addDependencyTo option, it is not needed if using postcss-loader >= v1.0.0 (#251)

8.2.0 - 2016-11-09

  • Fixed: Warn about all @imports after other CSS declarations (#240)
  • Added: dependency message (#241)

8.1.3 - 2016-11-03

  • Fixed: Nested import ordering (#236 - @RyanZim)

8.1.2 - 2016-05-07

  • Fixed: prevent JSPM to throw unrecoverable error (#205)

8.1.1 - 2016-05-04

  • Fixed: JSPM support (#194)

8.1.0 - 2016-04-04

  • Added: JSPM browser field (#186)

8.0.2 - 2015-01-27

  • Fixed: Comments between imports statements are ignored (#164)

8.0.1 - 2015-01-27

  • Fixed: missing "lib" folder (#161)

8.0.0 - 2015-01-27

All imports statements must be at the top of your file now, per CSS specification.
You should use postcss-reporter to see the warnings raised.

  • Removed: async mode/option (now async by default) (#107)
  • Removed: "bower_components" not supported by default anymore, use "path" option to add it back
  • Removed: encoding option. Encoding can be specified in custom load option
postcssImport({
  load: function(filename) {
    return fs.readFileSync(filename, "utf-8")
  }
})

(#144)

  • Removed: glob support (#146)

Globs can be implemented with custom resolve option

postcssImport({
  resolve: function(id, base) {
    return glob.sync(path.join(base, id))
  }
})

(#116)

  • Changed: custom resolve has more responsibility for paths resolving. See resolve option for more information about this change (#116)
  • Changed: support promise in transform option and undefined result will be skipped (#147)
  • Changed: options.plugins are applied to unprocessed ast before imports detecting (157)
  • Added: custom resolve function can return array of paths (#120)
  • Added: custom syntax in imported files support (#130)
  • Added: support custom load option (#144)
  • Added: detect css extension in package.json main field (153)

Note: _If you miss options/default behavior (glob etc), a new plugin will handle all those things. Please follow issue #145 _

7.1.3 - 2015-11-05

  • Fixed: ensure node 0.12 compatibility, round 2 (#93)

7.1.2 - 2015-11-05

  • Fixed: performance issue because of cloned options (#90)

7.1.1 - 2015-11-05

  • Added: ensure node 0.12 compatibility

7.0.0 - 2015-08-25

  • Removed: compatibility with postcss v4.x (#75)
  • Added: compatibility with postcss v5.x (#76)
  • Added: lighter package by upgrading some dependencies (#73)

6.2.0 - 2015-07-21

  • Added: skipDuplicates option now allows you to not skip duplicated files (#67)

6.1.1 - 2015-07-07

  • Fixed: Prevent mutability issue, round 2 (#44)
  • Added: plugins option, to run some postcss plugin on imported files (#55)
  • Added: bower_components is now part of the default paths (#66)
  • Added: async option allow to use enable PostCSS async API usage. Note that it's not enabling async fs read yet. It has been added to fix breaking change introduced by 6.1.0.

6.1.0 - 2015-07-07 YANKED

This release was not respecting semver and introduced a major breaking change. It has been unpublished for now.

6.0.0 - 2015-06-17

  • Changed: warnings messages are now using postcss message api (4.1.x)
  • Added: warning when a import statement has not been closed correctly (#42)

5.2.2 - 2015-04-19

  • Fixed: globbed imports work for module directories (#37)

5.2.1 - 2015-04-17

  • Fixed: glob import now works with single quote @import (#36)

5.2.0 - 2015-04-15

  • Added: glob pattern are now supported if glob option is set to true (#34)
  • Added: plugin can now be added to PostCSS without calling it as a function (#27)

5.1.1 - 2015-04-10

  • Fixed: regression of 5.1.0: files which only contain same @import rules were skip (#31)

5.1.0 - 2015-03-27

  • Added: files with the same content will only be imported once. Previously, only the full path was used to determine if a file has already been imported in a given scope. Now, we also test create a hash with the content of the file to check if a file with the same content has not already been imported. This might be usefull if some modules you import are importing the same library from different places (eg: normalize might be as dep for several modules located in different places in node_modules) (#29)

5.0.3 - 2015-02-16

  • Fixed: regression of 5.0.2: AST parent references were not updated (#25)

5.0.2 - 2015-02-14

  • Fixed: indentation and code style are now preserved (#20)

5.0.1 - 2015-02-13

  • Fixed: breaking bug with remote stylesheets (#21 & #22)

5.0.0 - 2015-01-26

  • Added: compatibility with postcss v4.x
  • Removed: compatibility with postcss v3.x
  • Fixed: relative imports (./ and ../) should work using path option only (no need for from) (#14)

4.1.1 - 2015-01-05

  • Fixed: irregular whitespace that throw syntax error in some environnements

4.1.0 - 2014-12-12

  • Added: web_modules is now in module directories that are used to resolve @import (#13).

4.0.0 - 2014-12-11

  • Added: windows compatibility (by building on AppVeyor)
  • Added: root option

3.2.0 - 2014-11-24

  • Added: onImport callback offers a way to get list of imported files (ref)

3.1.0 - 2014-11-24

  • Added: ability to consume local modules (fix #12)

3.0.0 - 2014-11-21

  • Added: ability to consume node modules (ref). This means you don't have to add node_modules in the path anymore (or using @import "../node_modules/..."). Also, index.css can be ommited.

This means something like this

@import "../node_modules/my-css-on-npm/index.css";

can be written like this

@import "my-css-on-npm";

Dependencies of dependencies should be resolved as well.

Note that npm resolution is done after the default local behavior.

  • Changed: When importing a file multiple times in the same scope (same level of media queries), file will only be imported the first time. This is done to avoid having multiples outputs of a npm dep used multiples times in different modules.

2.0.0 - 2014-11-12

  • Added: compatibility with postcss v3.x
  • Removed: compatibility with postcss v2.x

1.0.3 - 2014-10-29

  • Fixed: relative import path stack

1.0.2 - 2014-09-16

  • Added: Move ignored import at top & adjust related media queries, to make them work (fix #2)
  • Added: Ignore scheme-relative absolute URLs
  • Removed: parse-import module dependency

1.0.1 - 2014-08-26

  • Fixed: GNU message format
  • Added: Support empty files (cssnext/#24)

1.0.0 - 2014-08-10

✨ First release based on rework-import v1.2.0 (mainly for fixtures)