Copy all assets referenced in CSS to a folder, updating the URLs
Copy all assets referenced by the CSS document to a folder, updating the CSS references.
var rework = require('rework'),
assets = require('rework-assets');
var css = ...;
css = rework(css)
.use(assets({
src: 'src',
dest: 'assets'
}))
.toString();
// all assets are copied to the `assets` folder, which is referenced by all
// `url(...)` calls in the generated CSS
assets(options)
Returns a new rework plugin function that will copy all the assets referenced
by the CSS document to a folder. options
may contain the following values:
src
: The directory where the CSS source files are located. Defaults to thedest
: The output folder that will contain the copied assets. Defaults toprefix
: The URL that is used to prefix the urls from the generated CSS.retainName
: Append hash to the original asset name to make identification easier,onError
: A function that is called whenever an error occurs whil reading aonFile
: A function that is called whenever a file is included. It is calledfunc
: The name of the CSS function that references an asset in the input.'url'
. For example, if func: 'asset'
is specified, allasset(...)
calls will be found in the input and the copied to the output.url(...)
to reference the copied assets inThe path to each asset source is determined by the src
directory and the
position.source
property of each node that is set when parsing with
css-parse if position tracking is
enabled (this is the same information used for generating source maps). This
means that even if the source document is parsed from several files (for
example when using rework-npm), it
will still resolve the referenced asset using the source file path.
The destination file name is derived from a hash of the source file with the source extension appended. This allows multiple files to reference assets with the same name but different path. It also deduplicates files originating from multiple sources but containing the same content.
This is an example build script, showing how to use rework-assets
in
conjunction with other rework plugins. You can create your own build script
using Node.js directory or you can use a build tool such as
Grunt or Gulp.
#!/usr/bin/env node
var readSync = require('fs').readFileSync,
path = require('path'),
rework = require('rework');
// Rework plugins
var imports = require('rework-npm'),
assets = require('rework-assets'),
inherit = require('rework-inherit');
// `$ build-css src/index.css > build/build.css`
process.stdout.write(build(process.argv[2]));
function build (file) {
var styles = readSync(file, 'utf8'),
dir = path.dirname(file);
return rework(styles)
.use(imports({ dir: dir }))
.use(assets({
src: dir,
dest: path.join(__dirname, '../build/assets'),
prefix: 'assets/',
onError: console.error
}))
.use(inherit())
.toString();
}