postcss-modules 4.1.1 → 4.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.2.2
4
+
5
+ - Fix the build
6
+
7
+ ## 4.2.1
8
+
9
+ - Fixed the `resolve` option behaviour by @kamilic https://github.com/madyankin/postcss-modules/pull/127
10
+
11
+ ## 4.2.0
12
+
13
+ - Added the `resolve` option to configure lookup paths for composes/from by @kamilic https://github.com/madyankin/postcss-modules/pull/126
14
+
15
+ ## 4.1.3
16
+
17
+ - Fixed package contents
18
+
3
19
  ## 4.1.1
4
20
 
5
21
  - Fixed TypeScript typings by Shuman Lim (@origin-master) https://github.com/madyankin/postcss-modules/pull/124
package/README.md CHANGED
@@ -5,7 +5,15 @@ A [PostCSS] plugin to use [CSS Modules] everywhere. Not only at the client side.
5
5
  [postcss]: https://github.com/postcss/postcss
6
6
  [css modules]: https://github.com/css-modules/css-modules
7
7
 
8
- What is this? For example, you have the following CSS:
8
+ ## Support the developer
9
+
10
+ I maintain the plugin in my free time, so I don't receive any payment for this work.
11
+ To have better docs, new features and integrations with frameworks, you can [support me on Patreon](https://www.patreon.com/bePatron?u=25976212).
12
+
13
+
14
+ ## What is this?
15
+
16
+ For example, you have the following CSS:
9
17
 
10
18
  ```css
11
19
  /* styles.css */
@@ -203,6 +211,24 @@ Style of exported classnames, the keys in your json.
203
211
 
204
212
  In lieu of a string, a custom function can generate the exported class names.
205
213
 
214
+ ### Resolve path alias
215
+
216
+ You can rewrite paths for `composes/from` by using `resolve` options.
217
+ It's useful when you need to resolve custom path alias.
218
+
219
+ ```js
220
+ postcss([
221
+ require("postcss-modules")({
222
+ resolve: function (file) {
223
+ return file.replace(/^@/, process.cwd());
224
+ },
225
+ }),
226
+ ]);
227
+ ```
228
+
229
+ `resolve` may also return a `Promise<string>`.
230
+
231
+
206
232
  ## Integration with templates
207
233
 
208
234
  The plugin only transforms CSS classes to CSS modules.
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.behaviours = undefined;
7
+ exports.getDefaultPlugins = getDefaultPlugins;
8
+ exports.isValidBehaviour = isValidBehaviour;
9
+
10
+ var _postcssModulesLocalByDefault = require("postcss-modules-local-by-default");
11
+
12
+ var _postcssModulesLocalByDefault2 = _interopRequireDefault(_postcssModulesLocalByDefault);
13
+
14
+ var _postcssModulesExtractImports = require("postcss-modules-extract-imports");
15
+
16
+ var _postcssModulesExtractImports2 = _interopRequireDefault(_postcssModulesExtractImports);
17
+
18
+ var _postcssModulesScope = require("postcss-modules-scope");
19
+
20
+ var _postcssModulesScope2 = _interopRequireDefault(_postcssModulesScope);
21
+
22
+ var _postcssModulesValues = require("postcss-modules-values");
23
+
24
+ var _postcssModulesValues2 = _interopRequireDefault(_postcssModulesValues);
25
+
26
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
27
+
28
+ const behaviours = exports.behaviours = {
29
+ LOCAL: "local",
30
+ GLOBAL: "global"
31
+ };
32
+
33
+ function getDefaultPlugins({
34
+ behaviour,
35
+ generateScopedName,
36
+ exportGlobals
37
+ }) {
38
+ const scope = (0, _postcssModulesScope2.default)({ generateScopedName, exportGlobals });
39
+
40
+ const plugins = {
41
+ [behaviours.LOCAL]: [_postcssModulesValues2.default, _postcssModulesLocalByDefault2.default, _postcssModulesExtractImports2.default, scope],
42
+ [behaviours.GLOBAL]: [_postcssModulesValues2.default, _postcssModulesExtractImports2.default, scope]
43
+ };
44
+
45
+ return plugins[behaviour];
46
+ }
47
+
48
+ function isValidBehaviour(behaviour) {
49
+ return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
50
+ }
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+
7
+ var _postcss = require("postcss");
8
+
9
+ var _postcss2 = _interopRequireDefault(_postcss);
10
+
11
+ var _fs = require("fs");
12
+
13
+ var _fs2 = _interopRequireDefault(_fs);
14
+
15
+ var _path = require("path");
16
+
17
+ var _path2 = _interopRequireDefault(_path);
18
+
19
+ var _parser = require("./parser");
20
+
21
+ var _parser2 = _interopRequireDefault(_parser);
22
+
23
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24
+
25
+ // Copied from https://github.com/css-modules/css-modules-loader-core
26
+
27
+ class Core {
28
+ constructor(plugins) {
29
+ this.plugins = plugins || Core.defaultPlugins;
30
+ }
31
+
32
+ load(sourceString, sourcePath, trace, pathFetcher) {
33
+ let parser = new _parser2.default(pathFetcher, trace);
34
+
35
+ return (0, _postcss2.default)(this.plugins.concat([parser.plugin()])).process(sourceString, { from: "/" + sourcePath }).then(result => {
36
+ return {
37
+ injectableSource: result.css,
38
+ exportTokens: parser.exportTokens
39
+ };
40
+ });
41
+ }
42
+ }
43
+
44
+ // Sorts dependencies in the following way:
45
+ // AAA comes before AA and A
46
+ // AB comes after AA and before A
47
+ // All Bs come after all As
48
+ // This ensures that the files are always returned in the following order:
49
+ // - In the order they were required, except
50
+ // - After all their dependencies
51
+ const traceKeySorter = (a, b) => {
52
+ if (a.length < b.length) {
53
+ return a < b.substring(0, a.length) ? -1 : 1;
54
+ } else if (a.length > b.length) {
55
+ return a.substring(0, b.length) <= b ? -1 : 1;
56
+ } else {
57
+ return a < b ? -1 : 1;
58
+ }
59
+ };
60
+
61
+ class FileSystemLoader {
62
+ constructor(root, plugins) {
63
+ this.root = root;
64
+ this.sources = {};
65
+ this.traces = {};
66
+ this.importNr = 0;
67
+ this.core = new Core(plugins);
68
+ this.tokensByFile = {};
69
+ }
70
+
71
+ fetch(_newPath, relativeTo, _trace) {
72
+ let newPath = _newPath.replace(/^["']|["']$/g, ""),
73
+ trace = _trace || String.fromCharCode(this.importNr++);
74
+ return new Promise((resolve, reject) => {
75
+ let relativeDir = _path2.default.dirname(relativeTo),
76
+ rootRelativePath = _path2.default.resolve(relativeDir, newPath),
77
+ fileRelativePath = _path2.default.resolve(_path2.default.join(this.root, relativeDir), newPath);
78
+
79
+ // if the path is not relative or absolute, try to resolve it in node_modules
80
+ if (newPath[0] !== "." && newPath[0] !== "/") {
81
+ try {
82
+ fileRelativePath = require.resolve(newPath);
83
+ } catch (e) {
84
+ // noop
85
+ }
86
+ }
87
+
88
+ const tokens = this.tokensByFile[fileRelativePath];
89
+ if (tokens) {
90
+ return resolve(tokens);
91
+ }
92
+
93
+ _fs2.default.readFile(fileRelativePath, "utf-8", (err, source) => {
94
+ if (err) reject(err);
95
+ this.core.load(source, rootRelativePath, trace, this.fetch.bind(this)).then(({ injectableSource, exportTokens }) => {
96
+ this.sources[fileRelativePath] = injectableSource;
97
+ this.traces[trace] = fileRelativePath;
98
+ this.tokensByFile[fileRelativePath] = exportTokens;
99
+ resolve(exportTokens);
100
+ }, reject);
101
+ });
102
+ });
103
+ }
104
+
105
+ get finalSource() {
106
+ const traces = this.traces;
107
+ const sources = this.sources;
108
+ let written = new Set();
109
+
110
+ return Object.keys(traces).sort(traceKeySorter).map(key => {
111
+ const filename = traces[key];
112
+ if (written.has(filename)) {
113
+ return null;
114
+ }
115
+ written.add(filename);
116
+
117
+ return sources[filename];
118
+ }).join("");
119
+ }
120
+ }
121
+ exports.default = FileSystemLoader;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+
7
+ var _icssReplaceSymbols = require("icss-replace-symbols");
8
+
9
+ var _icssReplaceSymbols2 = _interopRequireDefault(_icssReplaceSymbols);
10
+
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+
13
+ // Copied from https://github.com/css-modules/css-modules-loader-core
14
+
15
+ const importRegexp = /^:import\((.+)\)$/;
16
+ class Parser {
17
+ constructor(pathFetcher, trace) {
18
+ this.pathFetcher = pathFetcher;
19
+ this.plugin = this.plugin.bind(this);
20
+ this.exportTokens = {};
21
+ this.translations = {};
22
+ this.trace = trace;
23
+ }
24
+
25
+ plugin() {
26
+ const parser = this;
27
+ return {
28
+ postcssPlugin: "css-modules-parser",
29
+ OnceExit(css) {
30
+ return Promise.all(parser.fetchAllImports(css)).then(() => parser.linkImportedSymbols(css)).then(() => parser.extractExports(css));
31
+ }
32
+ };
33
+ }
34
+
35
+ fetchAllImports(css) {
36
+ let imports = [];
37
+ css.each(node => {
38
+ if (node.type == "rule" && node.selector.match(importRegexp)) {
39
+ imports.push(this.fetchImport(node, css.source.input.from, imports.length));
40
+ }
41
+ });
42
+ return imports;
43
+ }
44
+
45
+ linkImportedSymbols(css) {
46
+ (0, _icssReplaceSymbols2.default)(css, this.translations);
47
+ }
48
+
49
+ extractExports(css) {
50
+ css.each(node => {
51
+ if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
52
+ });
53
+ }
54
+
55
+ handleExport(exportNode) {
56
+ exportNode.each(decl => {
57
+ if (decl.type == "decl") {
58
+ Object.keys(this.translations).forEach(translation => {
59
+ decl.value = decl.value.replace(translation, this.translations[translation]);
60
+ });
61
+ this.exportTokens[decl.prop] = decl.value;
62
+ }
63
+ });
64
+ exportNode.remove();
65
+ }
66
+
67
+ fetchImport(importNode, relativeTo, depNr) {
68
+ let file = importNode.selector.match(importRegexp)[1],
69
+ depTrace = this.trace + String.fromCharCode(depNr);
70
+ return this.pathFetcher(file, relativeTo, depTrace).then(exports => {
71
+ importNode.each(decl => {
72
+ if (decl.type == "decl") {
73
+ this.translations[decl.prop] = exports[decl.value];
74
+ }
75
+ });
76
+ importNode.remove();
77
+ }, err => console.log(err));
78
+ }
79
+ }
80
+ exports.default = Parser;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = generateScopedName;
7
+
8
+ var _stringHash = require("string-hash");
9
+
10
+ var _stringHash2 = _interopRequireDefault(_stringHash);
11
+
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+
14
+ function generateScopedName(name, filename, css) {
15
+ const i = css.indexOf(`.${name}`);
16
+ const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
17
+ const hash = (0, _stringHash2.default)(css).toString(36).substr(0, 5);
18
+
19
+ return `_${name}_${hash}_${lineNumber}`;
20
+ }
package/build/index.js ADDED
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+
3
+ var _postcss = require("postcss");
4
+
5
+ var _postcss2 = _interopRequireDefault(_postcss);
6
+
7
+ var _lodash = require("lodash.camelcase");
8
+
9
+ var _lodash2 = _interopRequireDefault(_lodash);
10
+
11
+ var _genericNames = require("generic-names");
12
+
13
+ var _genericNames2 = _interopRequireDefault(_genericNames);
14
+
15
+ var _unquote = require("./unquote");
16
+
17
+ var _unquote2 = _interopRequireDefault(_unquote);
18
+
19
+ var _parser = require("./css-loader-core/parser");
20
+
21
+ var _parser2 = _interopRequireDefault(_parser);
22
+
23
+ var _loader = require("./css-loader-core/loader");
24
+
25
+ var _loader2 = _interopRequireDefault(_loader);
26
+
27
+ var _generateScopedName = require("./generateScopedName");
28
+
29
+ var _generateScopedName2 = _interopRequireDefault(_generateScopedName);
30
+
31
+ var _saveJSON = require("./saveJSON");
32
+
33
+ var _saveJSON2 = _interopRequireDefault(_saveJSON);
34
+
35
+ var _behaviours = require("./behaviours");
36
+
37
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
38
+
39
+ function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
40
+
41
+ const PLUGIN_NAME = "postcss-modules";
42
+
43
+ function getDefaultScopeBehaviour(opts) {
44
+ if (opts.scopeBehaviour && (0, _behaviours.isValidBehaviour)(opts.scopeBehaviour)) {
45
+ return opts.scopeBehaviour;
46
+ }
47
+
48
+ return _behaviours.behaviours.LOCAL;
49
+ }
50
+
51
+ function getScopedNameGenerator(opts) {
52
+ const scopedNameGenerator = opts.generateScopedName || _generateScopedName2.default;
53
+
54
+ if (typeof scopedNameGenerator === "function") return scopedNameGenerator;
55
+ return (0, _genericNames2.default)(scopedNameGenerator, {
56
+ context: process.cwd(),
57
+ hashPrefix: opts.hashPrefix
58
+ });
59
+ }
60
+
61
+ function getLoader(opts, plugins) {
62
+ const root = typeof opts.root === "undefined" ? "/" : opts.root;
63
+ return typeof opts.Loader === "function" ? new opts.Loader(root, plugins) : new _loader2.default(root, plugins);
64
+ }
65
+
66
+ function isGlobalModule(globalModules, inputFile) {
67
+ return globalModules.some(regex => inputFile.match(regex));
68
+ }
69
+
70
+ function getDefaultPluginsList(opts, inputFile) {
71
+ const globalModulesList = opts.globalModulePaths || null;
72
+ const exportGlobals = opts.exportGlobals || false;
73
+ const defaultBehaviour = getDefaultScopeBehaviour(opts);
74
+ const generateScopedName = getScopedNameGenerator(opts);
75
+
76
+ if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
77
+ return (0, _behaviours.getDefaultPlugins)({
78
+ behaviour: _behaviours.behaviours.GLOBAL,
79
+ generateScopedName,
80
+ exportGlobals
81
+ });
82
+ }
83
+
84
+ return (0, _behaviours.getDefaultPlugins)({
85
+ behaviour: defaultBehaviour,
86
+ generateScopedName,
87
+ exportGlobals
88
+ });
89
+ }
90
+
91
+ function isOurPlugin(plugin) {
92
+ return plugin.postcssPlugin === PLUGIN_NAME;
93
+ }
94
+
95
+ function dashesCamelCase(string) {
96
+ return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
97
+ }
98
+
99
+ module.exports = (opts = {}) => {
100
+ return {
101
+ postcssPlugin: PLUGIN_NAME,
102
+ OnceExit(css, { result }) {
103
+ return _asyncToGenerator(function* () {
104
+ const getJSON = opts.getJSON || _saveJSON2.default;
105
+ const inputFile = css.source.input.file;
106
+ const pluginList = getDefaultPluginsList(opts, inputFile);
107
+ const resultPluginIndex = result.processor.plugins.findIndex(function (plugin) {
108
+ return isOurPlugin(plugin);
109
+ });
110
+ if (resultPluginIndex === -1) {
111
+ throw new Error('Plugin missing from options.');
112
+ }
113
+ const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
114
+ const loaderPlugins = [...earlierPlugins, ...pluginList];
115
+ const loader = getLoader(opts, loaderPlugins);
116
+ const fetcher = function fetcher(file, relativeTo, depTrace) {
117
+ const unquoteFile = (0, _unquote2.default)(file);
118
+ const resolvedResult = typeof opts.resolve === 'function' && opts.resolve(unquoteFile);
119
+ const resolvedFile = resolvedResult instanceof Promise ? resolvedResult : Promise.resolve(resolvedResult);
120
+
121
+ return resolvedFile.then(function (f) {
122
+ return loader.fetch.call(loader, `"${f || unquoteFile}"`, relativeTo, depTrace);
123
+ });
124
+ };
125
+ const parser = new _parser2.default(fetcher);
126
+
127
+ yield (0, _postcss2.default)([...pluginList, parser.plugin()]).process(css, {
128
+ from: inputFile
129
+ });
130
+
131
+ const out = loader.finalSource;
132
+ if (out) css.prepend(out);
133
+
134
+ if (opts.localsConvention) {
135
+ const isFunc = typeof opts.localsConvention === "function";
136
+
137
+ parser.exportTokens = Object.entries(parser.exportTokens).reduce(function (tokens, [className, value]) {
138
+ if (isFunc) {
139
+ tokens[opts.localsConvention(className, value, inputFile)] = value;
140
+
141
+ return tokens;
142
+ }
143
+
144
+ switch (opts.localsConvention) {
145
+ case "camelCase":
146
+ tokens[className] = value;
147
+ tokens[(0, _lodash2.default)(className)] = value;
148
+
149
+ break;
150
+ case "camelCaseOnly":
151
+ tokens[(0, _lodash2.default)(className)] = value;
152
+
153
+ break;
154
+ case "dashes":
155
+ tokens[className] = value;
156
+ tokens[dashesCamelCase(className)] = value;
157
+
158
+ break;
159
+ case "dashesOnly":
160
+ tokens[dashesCamelCase(className)] = value;
161
+
162
+ break;
163
+ }
164
+
165
+ return tokens;
166
+ }, {});
167
+ }
168
+
169
+ result.messages.push({
170
+ type: "export",
171
+ plugin: "postcss-modules",
172
+ exportTokens: parser.exportTokens
173
+ });
174
+
175
+ // getJSON may return a promise
176
+ return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
177
+ })();
178
+ }
179
+ };
180
+ };
181
+
182
+ module.exports.postcss = true;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = saveJSON;
7
+
8
+ var _fs = require("fs");
9
+
10
+ function saveJSON(cssFile, json) {
11
+ return new Promise((resolve, reject) => {
12
+ (0, _fs.writeFile)(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
13
+ });
14
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = unquote;
7
+ // copied from https://github.com/lakenen/node-unquote
8
+
9
+ var reg = /['"]/;
10
+
11
+ function unquote(str) {
12
+ if (!str) {
13
+ return "";
14
+ }
15
+ if (reg.test(str.charAt(0))) {
16
+ str = str.substr(1);
17
+ }
18
+ if (reg.test(str.charAt(str.length - 1))) {
19
+ str = str.substr(0, str.length - 1);
20
+ }
21
+ return str;
22
+ }
package/index.d.ts CHANGED
@@ -48,6 +48,8 @@ declare interface Options {
48
48
  root?: string;
49
49
 
50
50
  Loader?: typeof Loader;
51
+
52
+ resolve?: (file: string) => string | Promise<string>;
51
53
  }
52
54
 
53
55
  declare interface PostcssModulesPlugin {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "postcss-modules",
3
- "version": "4.1.1",
3
+ "version": "4.2.2",
4
4
  "description": "PostCSS plugin to use CSS Modules everywhere",
5
5
  "main": "build/index.js",
6
6
  "types": "index.d.ts",
@@ -47,11 +47,7 @@
47
47
  "prettier": "^2.0.5"
48
48
  },
49
49
  "scripts": {
50
- "pretest": "$(npm bin)/eslint src test",
51
- "test": "$(npm bin)/jest",
52
- "transpile": "$(npm bin)/babel src -d build",
53
- "prepublish": "npm run transpile",
54
- "postpublish": "rm -rf build && git push --follow-tags",
50
+ "test": "make test",
55
51
  "precommit": "lint-staged"
56
52
  },
57
53
  "lint-staged": {
package/.browserslistrc DELETED
@@ -1,3 +0,0 @@
1
- ie 9
2
- firefox 4
3
- safari 8
@@ -1,28 +0,0 @@
1
- name: Test
2
-
3
- env:
4
- FORCE_COLOR: "1"
5
-
6
- on:
7
- push:
8
- pull_request:
9
-
10
- jobs:
11
- build:
12
-
13
- runs-on: ubuntu-latest
14
-
15
- strategy:
16
- matrix:
17
- node-version: [10.x, 12.x, 14.x, 15.x]
18
- # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
19
-
20
- steps:
21
- - uses: actions/checkout@v2
22
- - name: Use Node.js ${{ matrix.node-version }}
23
- uses: actions/setup-node@v1
24
- with:
25
- node-version: ${{ matrix.node-version }}
26
- - run: npm ci
27
- - run: npm run build --if-present
28
- - run: npm test