diff --git a/README.md b/README.md index cd26a79..2b45d97 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,13 @@ } ``` + +## Installation + +```bash +npm i -D postcss postcss-image-inliner +``` + ## Usage ```js diff --git a/index.js b/index.js index 8bd0945..4f606d5 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,5 @@ 'use strict'; -const postcss = require('postcss'); const debug = require('debug')('image-inliner'); const escapeRegExp = require('escape-string-regexp'); const {getDataUriMapping} = require('./lib/image'); @@ -22,39 +21,44 @@ const loop = (cb) => { }; }; -module.exports = postcss.plugin('postcss-image-inliner', (options_ = {}) => { +module.exports = (options_ = {}) => { const options = {...DEFAULTS, ...options_}; options.assetPaths = Array.isArray(options.assetPaths) ? [...options.assetPaths, process.cwd()] : [options.assetPaths, process.cwd()]; - return async (css) => { - const urls = new Set([]); - const filter = /^(background(?:-image)?)|(content)|(cursor)/; - // Get urls - css.walkDecls( - filter, - loop(({url}) => urls.add(url)) - ); - - const mapping = await getDataUriMapping([...urls], options); - - css.walkDecls( - filter, - loop(({decl, url}) => { - if (mapping[url]) { - const regexp = new RegExp(`['"]?${escapeRegExp(url)}['"]?`, 'gm'); - - decl.value = decl.value.replace(regexp, `'${mapping[url]}'`); - debug(url, 'successfully replaced with ', mapping[url]); - } else { - debug(url, 'failed'); - if (options_.strict) { - throw new Error(`No file found for ${url}`); + return { + postcssPlugin: 'postcss-image-inliner', + async Once(root) { + const urls = new Set([]); + const filter = /^(background(?:-image)?)|(content)|(cursor)/; + // Get urls + root.walkDecls( + filter, + loop(({url}) => urls.add(url)) + ); + + const mapping = await getDataUriMapping([...urls], options); + + root.walkDecls( + filter, + loop(({decl, url}) => { + if (mapping[url]) { + const regexp = new RegExp(`['"]?${escapeRegExp(url)}['"]?`, 'gm'); + + decl.value = decl.value.replace(regexp, `'${mapping[url]}'`); + debug(url, 'successfully replaced with ', mapping[url]); + } else { + debug(url, 'failed'); + if (options_.strict) { + throw new Error(`No file found for ${url}`); + } } - } - }) - ); + }) + ); + }, }; -}); +}; + +module.exports.postcss = true; diff --git a/package.json b/package.json index b8c0ef0..7ca500e 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,6 @@ "debug": "^4.3.1", "escape-string-regexp": "^4.0.0", "filesize": "^6.1.0", - "postcss": "^8.3.0", "svgo": "^1.3.2" }, "devDependencies": { @@ -33,8 +32,12 @@ "finalhandler": "^1.1.2", "mocha": "^8.2.1", "serve-static": "^1.14.1", + "postcss": "^8.3.0", "xo": "^0.39.1" }, + "peerDependencies": { + "postcss": "^8.3.0" + }, "scripts": { "xo": "xo", "mocha": "mocha",