Skip to content

Commit f80c517

Browse files
committed
Add CSS modules cache
It'd allow running the plugin in gulp watch and other similar tools, where files with CSS modules might change between runs. Related issue: #5
1 parent baa90e4 commit f80c517

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

lib/cssModules.es6

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ import path from 'path';
33
import _get from 'lodash.get';
44
import parseAttrs from 'posthtml-attrs-parser';
55

6+
let cssModulesCache = {};
67

78
export default (cssModulesPath) => {
89
return function cssModules(tree) {
10+
// If the plugin is used in gulp watch or another similar tool, files with CSS modules
11+
// might change between runs. Therefore we purge the cache before each run.
12+
cssModulesCache = {};
913
tree.match({attrs: {'css-module': /\w+/}}, node => {
1014
const attrs = parseAttrs(node.attrs);
1115
const cssModuleName = attrs['css-module'];
@@ -30,7 +34,7 @@ function getCssClassName(cssModulesPath, cssModuleName) {
3034
cssModulesPath = path.join(cssModulesDir, cssModulesFile);
3135
}
3236

33-
const cssModules = require(path.resolve(cssModulesPath));
37+
const cssModules = getCssModules(path.resolve(cssModulesPath));
3438
const cssClassName = _get(cssModules, cssModuleName);
3539
if (! cssClassName) {
3640
throw getError('CSS module "' + cssModuleName + '" is not found');
@@ -42,6 +46,17 @@ function getCssClassName(cssModulesPath, cssModuleName) {
4246
}
4347

4448

49+
function getCssModules(cssModulesPath) {
50+
let fullPath = require.resolve(cssModulesPath);
51+
if (! cssModulesCache[fullPath]) {
52+
delete require.cache[fullPath];
53+
cssModulesCache[fullPath] = require(fullPath);
54+
}
55+
56+
return cssModulesCache[fullPath];
57+
}
58+
59+
4560
function getError(message) {
4661
const fullMessage = '[posthtml-css-modules] ' + message;
4762
return new Error(fullMessage);

0 commit comments

Comments
 (0)