UNPKG

1.98 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, relativePathFor, makeAssetId } = require('./utils/general');
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
20 Required options:
21 idGen
22 stripPath
23 outputFile
24
25 Optional:
26 moduleExport
27 annotation
28*/
29function InlinePacker(inputNode, options = {}) {
30 CachingWriter.call(this, [inputNode], {
31 name: 'InlinePacker',
32 annotation: options.annotation,
33 });
34
35 this.options = _.defaults(options, {
36 moduleExport: true
37 });
38}
39
40InlinePacker.prototype = Object.create(CachingWriter.prototype);
41InlinePacker.prototype.constructor = InlinePacker;
42
43InlinePacker.prototype.build = function() {
44 let { stripPath, idGen } = this.options;
45 let inputPath = this.inputPaths[0];
46 let idFor = _.partial(makeAssetId, _, stripPath, idGen);
47 let assetsStore = _(filePathsOnlyFor(this.listFiles()))
48 .map((filePath) => [
49 idFor(relativePathFor(filePath, inputPath)),
50 svgDataFor(fs.readFileSync(filePath, 'UTF-8'))
51 ])
52 .fromPairs()
53 .value();
54
55 this.saveAsJson(assetsStore, this.outputPath, this.options);
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;