• Stars
    star
    373
  • Rank 110,531 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 2 years ago

Reviews

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

Repository Details

PostCSS plugin to rebase url(), inline or copy asset.

postcss-url

Travis Build Status AppVeyor Build Status dependencies Status devDependencies Status

PostCSS plugin to rebase, inline or copy on url().

Installation

$ npm install postcss postcss-url

Basic example - rebase

// dependencies
const fs = require("fs")
const postcss = require("postcss")
const url = require("postcss-url")

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

// process css
const output = postcss()
  .use(url({
    url: "rebase"
  }))
  .process(css, {
    from: "src/stylesheet/index.css",
    to: "dist/index.css"
  })

before:

.element {
    background: url('images/sprite.png');
}

after:

.element {
    /* rebasing path by new destination */
    background: url('../src/stylesheet/images/sprite.png');
}

Inline

// postcss-url options
const options = {
    url: 'inline'
};

postcss()
  .use(url(options))
  .process(css, {
    from: "src/stylesheet/index.css",
    to: "dist/index.css"
  })

before:

.element {
    background: url('/images/sprite.png');
    filter: url('/images/circle.svg');
}

after:

.element {
    /* inlined png as base64 */
    background: url('data:image/png;base64,R0lGODlhAQABAJH/AP///wAAAP///wAAACH/C0FET0JFOklSMS4');
    /* inlined svg as encodeURIComponent */
    filter: url('data:image/svg+xml,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%2F%3E');
}

Copy

// postcss-url options
const options = {
    url: 'copy',
    // base path to search assets from
    basePath: path.resolve('node_modules/bootstrap'),
    // dir to copy assets
    assetsPath: 'img',
    // using hash names for assets (generates from asset content)
    useHash: true
};

postcss()
  .use(url(options))
  .process(css, {
    from: "src/stylesheet/index.css",
    to: "dist/index.css"
  })

before:

.element {
    background: url('/images/sprite.png');
}

after:

.element {
    /* copy 'sprite.png' from 'node_modules/bootstrap/images/' to 'dist/img/' */
    /* and rename it by hash function */
    background: url('img/a2ds3kfu.png');
}

Multiple options

process first matched option by default. multi: true in custom will processing with other options

const options = [
    { filter: '**/assets/copy/*.png', url: 'copy', assetsPath: 'img', useHash: true },
    { filter: '**/assets/inline/*.svg', url: 'inline' },
    { filter: '**/assets/**/*.gif', url: 'rebase' },
    // using custom function to build url
    { filter: 'cdn/**/*', url: (asset) => `https://cdn.url/${asset.url}` }
];

postcss().use(url(options))

Checkout tests for examples.

Options combinations

  • rebase - default
    • assetsPath - directory to copy assets (relative to to or absolute)
  • inline
    • basePath - path or array of paths to search assets (relative to from, or absolute)
    • encodeType - base64, encodeURI, encodeURIComponent
    • includeUriFragment - include the fragment identifer at the end of the URI
    • maxSize - file size in kbytes
    • fallback - copy, rebase or custom function for files > maxSize
    • ignoreFragmentWarning - do not warn when an SVG URL with a fragment is inlined
    • optimizeSvgEncode - reduce size of inlined svg (IE9+, Android 3+)
  • copy
    • basePath - path or array of paths to search assets (relative to from, or absolute)
    • assetsPath - directory to copy assets (relative to to or absolute)
    • useHash - use filehash(xxhash) for naming
    • hashOptions - options for hash function
  • custom {Function}
    • multi - processing with other options

Options list

url

rebase - (default)

Allow you to fix url() according to postcss to and/or from options (rebase to to first if available, otherwise from or process.cwd()).

inline

Allow you to inline assets using base64 encoding. Can use postcss from option to find ressources.

copy

Allow you to copy and rebase assets according to postcss to, assetsPath and from options (assetsPath is relative to the option to).

url: {Function}

Custom transform function. Takes following arguments:

  • asset
    • url - original url
    • pathname - url pathname (url without search or hash)
    • absolutePath - absolute path to asset
    • relativePath - current relative path to asset
    • search - search from url, ex. ?query=1 from ./image.png?query=1
    • hash - hash from url, ex. #spriteLink from ../asset.svg#spriteLink
  • dir
    • from - postcss option from
    • to - postcss option to
    • file - decl file path
  • options - postcss-url matched options
  • decl - related postcss declaration object
  • warn - wrapped function result.warn for current decl
  • result – postcss result object

And should return the transformed url. You can use this option to adjust urls for CDN.

maxSize

Specify the maximum file size to inline (in kbytes)

ignoreFragmentWarning

(default: false)

Do not warn when an SVG URL with a fragment is inlined. PostCSS-URL does not support partial inlining. The entire SVG file will be inlined. By default a warning will be issued when this occurs.

NOTE: Only files less than the maximum size will be inlined.

filter

A regular expression e.g. /\.svg$/, a minimatch string e.g. '**/*.svg' or a custom filter function to determine wether a file should be inlined.

fallback

The url fallback method to use if max size is exceeded or url contains a hash. Custom transform functions are supported.

includeUriFragment

(default: false)

Specifies whether the URL's fragment identifer value, if present, will be added to the inlined data URI.

basePath

Specify the base path or list of base paths where to search images from

assetsPath

(default: false)

If you specify an assetsPath, the assets files will be copied in that destination

useHash

(default: false)

If set to true the copy method is going to rename the path of the files by a hash name

hashOptions

method

(default: xxhash32)

Hash method xxhash32|xxhash64 or custom function (accept file buffer)

shrink

(default: 8)

Result hash shrink count

append

(default: false)

Prepend the original filename in resulting filename


Contributing

Work on a branch, install dev-dependencies, respect coding style & run tests before submitting a bug fix or a feature.

$ git clone https://github.com/postcss/postcss-url.git
$ git checkout -b patch-1
$ npm install
$ 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-import

PostCSS plugin to inline at-import rules content
JavaScript
1,352
star
4

postcss-nested

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

postcss-100vh-fix

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

postcss-cli

CLI for postcss
JavaScript
808
star
7

gulp-postcss

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

sugarss

Indent-based CSS syntax for PostCSS
JavaScript
698
star
9

postcss-js

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

postcss-scss

SCSS parser for PostCSS.
JavaScript
635
star
11

postcss-load-config

Autoload Config for PostCSS
JavaScript
618
star
12

postcss-custom-properties

Use Custom Properties in CSS
JavaScript
598
star
13

postcss-bem-linter

A BEM linter for postcss
JavaScript
561
star
14

postcss-mixins

PostCSS plugin for mixins
JavaScript
446
star
15

postcss-simple-vars

PostCSS plugin for Sass-like variables
JavaScript
409
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