UNPKG

1.33 kBJavaScriptView Raw
1'use strict';
2
3/**
4 Packages SVGs as ES modules for use with the inline strategy.
5 Required options:
6 makeAssetID
7
8 Examples of input and output:
9 Input node:
10 ├── alarm.svg
11 └── cat.svg
12
13 Output node:
14 inlined
15 ├── alarm.js
16 └── cat.js
17
18 alarm.js can content:
19
20 export default {
21 content: '<path>', attrs: { viewBox: '' }
22 }
23*/
24const path = require('path-posix');
25const CachingWriter = require('broccoli-caching-writer');
26const {
27 readFile, svgDataFor, toPosixPath, saveToFile, relativePathFor
28} = require('./utils');
29
30class InlinePacker extends CachingWriter {
31 constructor(inputNode, opts) {
32 super([inputNode], { name: 'InlinePacker' });
33 this.options = opts;
34 }
35
36 build() {
37 let inputPath = toPosixPath(this.inputPaths[0]);
38 let outputPath = path.join(toPosixPath(this.outputPath), 'inlined');
39 let { makeAssetID } = this.options;
40
41 this.listFiles()
42 .forEach((_filePath) => {
43 let filePath = toPosixPath(_filePath);
44 let relativePath = relativePathFor(filePath, inputPath);
45 let modulePath = path.join(outputPath, `${makeAssetID(relativePath)}.js`);
46 let svgData = svgDataFor(readFile(filePath));
47
48 saveToFile(modulePath, `export default ${JSON.stringify(svgData)}`);
49 });
50 }
51}
52
53module.exports = InlinePacker;