• Stars
    star
    1,352
  • Rank 33,428 (Top 0.7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PostCSS plugin to inline at-import rules content

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) 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.

nameLayer

Type: Function Default: null

You can provide a custom naming function for anonymous layers (@import 'baz.css' layer;). This function gets (index, rootFilename) arguments and should return a unique string.

This option only influences imports without a layer name. Without this option the plugin will warn on anonymous layers.

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

More Repositories

1

postcss

Transforming styles with JS plugins
TypeScript
27,948
star
2

autoprefixer

Parse CSS and add vendor prefixes to rules by Can I Use
JavaScript
21,460
star
3

postcss-nested

PostCSS plugin to unwrap nested rules like how Sass does it.
JavaScript
1,108
star
4

postcss-100vh-fix

PostCSS plugin to fix height/min-height: 100vh on iOS
JavaScript
911
star
5

postcss-cli

CLI for postcss
JavaScript
808
star
6

gulp-postcss

Pipe CSS through PostCSS processors with a single parse
JavaScript
771
star
7

sugarss

Indent-based CSS syntax for PostCSS
JavaScript
698
star
8

postcss-js

PostCSS for React Inline Styles, Free Style and other CSS-in-JS
JavaScript
643
star
9

postcss-scss

SCSS parser for PostCSS.
JavaScript
635
star
10

postcss-load-config

Autoload Config for PostCSS
JavaScript
618
star
11

postcss-custom-properties

Use Custom Properties in CSS
JavaScript
598
star
12

postcss-bem-linter

A BEM linter for postcss
JavaScript
561
star
13

postcss-mixins

PostCSS plugin for mixins
JavaScript
446
star
14

postcss-simple-vars

PostCSS plugin for Sass-like variables
JavaScript
409
star
15

postcss-url

PostCSS plugin to rebase url(), inline or copy asset.
JavaScript
373
star
16

postcss-color-function

PostCSS plugin to transform W3C CSS color function to more compatible CSS
JavaScript
323
star
17

postcss-media-minmax

Writing simple and graceful Media Queries!
JavaScript
290
star
18

postcss-plugin-boilerplate

PostCSS Plugin Boilerplate
JavaScript
220
star
19

postcss-calc

PostCSS plugin to reduce calc()
JavaScript
208
star
20

postcss-selector-parser

A CSS selector parser, integrates with postcss but does not require it.
JavaScript
196
star
21

postcss-reporter

Log PostCSS messages in the console
JavaScript
154
star
22

postcss-use

Enable PostCSS plugins directly in your stylesheet.
JavaScript
148
star
23

postcss-dark-theme-class

PostCSS plugin to make dark/light theme switcher by copying styles from media query to special class
JavaScript
147
star
24

postcss-easings

PostCSS plugin to replace easing names to cubic-bezier()
JavaScript
144
star
25

postcss-focus

PostCSS plugin to add :focus selector to every :hover for keyboard accessibility
JavaScript
116
star
26

postcss-safe-parser

Fault tolerant CSS parser for PostCSS
JavaScript
115
star
27

benchmark

PostCSS benchmarks
JavaScript
114
star
28

postcss-devtools

Log execution time for each plugin in a PostCSS instance.
JavaScript
92
star
29

postcss.org

Official website for PostCSS
JavaScript
81
star
30

postcss-browser-reporter

Plugin to display warning messages right in your browser
JavaScript
75
star
31

postcss-color-rebeccapurple

PostCSS plugin to transform rebeccapurple color to rgb()
JavaScript
62
star
32

postcss-deno

Postcss for Deno
JavaScript
56
star
33

postcss-brand-colors

PostCSS plugin to insert branding colors of all the major companies
JavaScript
54
star
34

postcss-size

PostCSS plugin for size shortcut
JavaScript
52
star
35

postcss-will-change

PostCSS plugin to insert 3D hack before will-change property
JavaScript
51
star
36

postcss-color-rgba-fallback

PostCSS plugin to transform rgba() to hexadecimal.
JavaScript
50
star
37

postcss-selector-matches

PostCSS plugin to transform :matches() W3C CSS pseudo class to more compatible CSS (simpler selectors)
JavaScript
44
star
38

postcss-plugin-context

Limit a PostCSS processor to a local stylesheet context.
JavaScript
33
star
39

postcss-color-hex-alpha

Use 4 & 8 character hex color notation in CSS
JavaScript
28
star
40

postcss-color-gray

Use the gray() color function in CSS
JavaScript
27
star
41

postcss-font-variant

PostCSS plugin to transform W3C CSS font variant properties to more compatible CSS (font-feature-settings)
JavaScript
25
star
42

brand

PostCSS branding files
JavaScript
24
star
43

postcss-filter-plugins

Exclude/warn on duplicated PostCSS plugins.
JavaScript
23
star
44

postcss-parser-tests

Base tests for every PostCSS CSS parser
JavaScript
21
star
45

postcss-color-hwb

PostCSS plugin to transform W3C CSS hwb() function to more compatible CSS (rgb() or rgba()).
JavaScript
21
star
46

eslint-config-postcss

An ESLint shareable config for postcss and plugins
JavaScript
18
star
47

postcss-plugin-suggestion-box

Suggestion box for PostCSS plugins
14
star
48

postcss-relative-opacity

PostCSS plugin to add opacity to any colors with Relative Color Syntax
JavaScript
11
star
49

fly-postcss

UNMAINTAINED
10
star
50

postcss-fail-on-warn

PostCSS plugin throws a error on any warning from previous PostCSS plugins.
JavaScript
8
star
51

postcss-sharec-config

Best parctices and configs from PostCSS plugin
7
star
52

postcss-at-rule-parser

A modern CSS at rule parser in PostCSS.
TypeScript
5
star
53

postcss-color

DEPRECATED - PostCSS plugin to transform latest W3C CSS color module syntax to more compatible CSS
JavaScript
5
star
54

postcss-deno-import

postcss-import plugin for Deno
JavaScript
4
star