forked from coralproject/talk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcss-overrides.js
77 lines (64 loc) · 2.34 KB
/
css-overrides.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Alley system for adding custom styles to Coral's CSS imports
*/
const path = require('path');
const fs = require('fs-extra');
const watch = require('glob-watcher');
const md5Hex = require('md5-hex');
const webpack = require('webpack');
function appendTmpCssOverride(oldPath, newPath, tmpPath) {
// Copy old CSS to temp dir
// @todo Account for duplicate file basenames
fs.copySync(oldPath, tmpPath, { overwrite: true });
// Append new file to old file
const newStylesStr = "\n\n" + fs.readFileSync(newPath, { encoding: 'utf8' });
fs.appendFileSync(tmpPath, newStylesStr);
}
function watchFiles(newPathsMap) {
const watcher = watch(Object.keys(newPathsMap));
watcher.on('change', (path) => {
if (newPathsMap.hasOwnProperty(path)) {
const { newPath, oldPath, tmpPath } = newPathsMap[path];
appendTmpCssOverride(oldPath, newPath, tmpPath);
}
});
}
function doCssOverrides() {
const plugins = [];
const cssOverrides = fs.readJsonSync(path.resolve(__dirname, 'css-overrides.json'), { throws: false });
if (cssOverrides && cssOverrides.length) {
// Set up temp css overrides dir
const tmpCssDirPath = path.resolve(__dirname, 'tmp-css-overrides');
fs.ensureDirSync(tmpCssDirPath);
const newPathsMap = {};
cssOverrides.forEach(({ oldPath, newPath }) => {
// Must both be CSS files
if (oldPath.endsWith('.css') && newPath.endsWith('.css')) {
console.log(`
Appending ${newPath} to ${oldPath}
`);
const regExpStr = oldPath
.split('/')
.join('\\/')
.replace('.css', '\\.css$');
const oldPathHash = md5Hex(oldPath).slice(0,5);
const tmpPath = path.join(tmpCssDirPath, `${oldPathHash}_${path.basename(oldPath)}`);
appendTmpCssOverride(oldPath, newPath, tmpPath);
// Add Webpack plugin instance to output array
plugins.push(new webpack.NormalModuleReplacementPlugin(
new RegExp(regExpStr),
path.resolve(__dirname, tmpPath)
));
// Add replaced paths to map
newPathsMap[path.resolve(__dirname, newPath)] = { newPath, oldPath, tmpPath };
}
});
if (process.env.NODE_ENV !== 'production') {
watchFiles(newPathsMap);
}
} else {
console.log('css-overrides.json not found or invalid');
}
return plugins;
}
module.exports = doCssOverrides;