UNPKG

2.06 kBJavaScriptView Raw
1const path = require('path');
2const fs = require('fs');
3const _ = require('lodash');
4const CachingWriter = require('broccoli-caching-writer');
5const mkdirp = require('mkdirp');
6const svgDataFor = require('./utils/svg-data-for');
7const { filePathsOnlyFor, idGenPathFor } = require('./utils/filepath');
8
9/**
10 SVG assets packer for `inline` strategy.
11 It concatenates inputNode files into a single JSON file like:
12
13 {
14 'asset-1-id': { content: '<path>', attrs: { viewBox: '' } },
15 'asset-2-id': { content: '<path>', attrs: { viewBox: '' } }
16 }
17
18 The file can optionally include ES6 module export.
19*/
20function InlinePacker(inputNode, options = {}) {
21 if (!options.outputFile) {
22 throw new Error('the outputFile option is required');
23 }
24
25 CachingWriter.call(this, [inputNode], {
26 name: 'InlinePacker',
27 annotation: options.annotation,
28 });
29
30 this.options = _.defaults(options, {
31 moduleExport: true
32 });
33}
34
35InlinePacker.prototype = Object.create(CachingWriter.prototype);
36InlinePacker.prototype.constructor = InlinePacker;
37
38InlinePacker.prototype.build = function() {
39 let assetsStore = this.buildAssetsStore(
40 filePathsOnlyFor(this.listFiles()), this.inputPaths[0], this.options
41 );
42
43 this.saveAsJson(assetsStore, this.outputPath, this.options);
44};
45
46InlinePacker.prototype.buildAssetsStore = function(filePaths, inputPath, options) {
47 let { stripPath, idGen, idGenOpts } = options;
48
49 return _(filePaths)
50 .map((filePath) => [
51 idGen(idGenPathFor(filePath, inputPath, stripPath), idGenOpts),
52 svgDataFor(fs.readFileSync(filePath, 'UTF-8'))
53 ])
54 .fromPairs()
55 .value();
56};
57
58InlinePacker.prototype.saveAsJson = function(data, outputPath, options) {
59 let { outputFile, moduleExport } = options;
60 let outputFilePath = path.join(outputPath, outputFile);
61 let jsonContent = JSON.stringify(data);
62
63 if (moduleExport) {
64 jsonContent = `export default ${jsonContent}`;
65 }
66
67 mkdirp.sync(path.dirname(outputFilePath));
68 fs.writeFileSync(outputFilePath, jsonContent);
69};
70
71module.exports = InlinePacker;