less-loader 10.1.0

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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright JS Foundation and other contributors
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ 'Software'), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,611 @@
1
+ <div align="center">
2
+ <a href="https://github.com/webpack/webpack">
3
+ <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
4
+ </a>
5
+ </div>
6
+
7
+ [![npm][npm]][npm-url]
8
+ [![node][node]][node-url]
9
+ [![deps][deps]][deps-url]
10
+ [![tests][tests]][tests-url]
11
+ [![cover][cover]][cover-url]
12
+ [![chat][chat]][chat-url]
13
+ [![size][size]][size-url]
14
+
15
+ # less-loader
16
+
17
+ A Less loader for webpack. Compiles Less to CSS.
18
+
19
+ ## Getting Started
20
+
21
+ To begin, you'll need to install `less` and `less-loader`:
22
+
23
+ ```console
24
+ $ npm install less less-loader --save-dev
25
+ ```
26
+
27
+ Then add the loader to your `webpack` config. For example:
28
+
29
+ **webpack.config.js**
30
+
31
+ ```js
32
+ module.exports = {
33
+ module: {
34
+ rules: [
35
+ {
36
+ test: /\.less$/i,
37
+ loader: [
38
+ // compiles Less to CSS
39
+ "style-loader",
40
+ "css-loader",
41
+ "less-loader",
42
+ ],
43
+ },
44
+ ],
45
+ },
46
+ };
47
+ ```
48
+
49
+ And run `webpack` via your preferred method.
50
+
51
+ ## Options
52
+
53
+ | Name | Type | Default | Description |
54
+ | :---------------------------------------: | :------------------: | :----------------------: | :----------------------------------------------------- |
55
+ | **[`lessOptions`](#lessoptions)** | `{Object\|Function}` | `{ relativeUrls: true }` | Options for Less. |
56
+ | **[`additionalData`](#additionalData)** | `{String\|Function}` | `undefined` | Prepends/Appends `Less` code to the actual entry file. |
57
+ | **[`sourceMap`](#sourcemap)** | `{Boolean}` | `compiler.devtool` | Enables/Disables generation of source maps. |
58
+ | **[`webpackImporter`](#webpackimporter)** | `{Boolean}` | `true` | Enables/Disables the default Webpack importer. |
59
+ | **[`implementation`](#implementation)** | `{Object\|String}` | `less` | Setup Less implementation to use. |
60
+
61
+ ### `lessOptions`
62
+
63
+ Type: `Object|Function`
64
+ Default: `{ relativeUrls: true }`
65
+
66
+ You can pass any Less specific options to the `less-loader` through the `lessOptions` property in the [loader options](https://webpack.js.org/configuration/module/#rule-options-rule-query). See the [Less documentation](http://lesscss.org/usage/#command-line-usage-options) for all available options in dash-case. Since we're passing these options to Less programmatically, you need to pass them in camelCase here:
67
+
68
+ #### `Object`
69
+
70
+ Use an object to pass options through to Less.
71
+
72
+ **webpack.config.js**
73
+
74
+ ```js
75
+ module.exports = {
76
+ module: {
77
+ rules: [
78
+ {
79
+ test: /\.less$/i,
80
+ use: [
81
+ {
82
+ loader: "style-loader",
83
+ },
84
+ {
85
+ loader: "css-loader",
86
+ },
87
+ {
88
+ loader: "less-loader",
89
+ options: {
90
+ lessOptions: {
91
+ strictMath: true,
92
+ },
93
+ },
94
+ },
95
+ ],
96
+ },
97
+ ],
98
+ },
99
+ };
100
+ ```
101
+
102
+ #### `Function`
103
+
104
+ Allows setting the options passed through to Less based off of the loader context.
105
+
106
+ ```js
107
+ module.exports = {
108
+ module: {
109
+ rules: [
110
+ {
111
+ test: /\.less$/i,
112
+ use: [
113
+ "style-loader",
114
+ "css-loader",
115
+ {
116
+ loader: "less-loader",
117
+ options: {
118
+ lessOptions: (loaderContext) => {
119
+ // More information about available properties https://webpack.js.org/api/loaders/
120
+ const { resourcePath, rootContext } = loaderContext;
121
+ const relativePath = path.relative(rootContext, resourcePath);
122
+
123
+ if (relativePath === "styles/foo.less") {
124
+ return {
125
+ paths: ["absolute/path/c", "absolute/path/d"],
126
+ };
127
+ }
128
+
129
+ return {
130
+ paths: ["absolute/path/a", "absolute/path/b"],
131
+ };
132
+ },
133
+ },
134
+ },
135
+ ],
136
+ },
137
+ ],
138
+ },
139
+ };
140
+ ```
141
+
142
+ ### `additionalData`
143
+
144
+ Type: `String|Function`
145
+ Default: `undefined`
146
+
147
+ Prepends `Less` code before the actual entry file.
148
+ In this case, the `less-loader` will not override the source but just **prepend** the entry's content.
149
+
150
+ This is especially useful when some of your Less variables depend on the environment:
151
+
152
+ > ℹ Since you're injecting code, this will break the source mappings in your entry file. Often there's a simpler solution than this, like multiple Less entry files.
153
+
154
+ #### `String`
155
+
156
+ ```js
157
+ module.exports = {
158
+ module: {
159
+ rules: [
160
+ {
161
+ test: /\.less$/i,
162
+ use: [
163
+ "style-loader",
164
+ "css-loader",
165
+ {
166
+ loader: "less-loader",
167
+ options: {
168
+ additionalData: `@env: ${process.env.NODE_ENV};`,
169
+ },
170
+ },
171
+ ],
172
+ },
173
+ ],
174
+ },
175
+ };
176
+ ```
177
+
178
+ #### `Function`
179
+
180
+ ##### Sync
181
+
182
+ ```js
183
+ module.exports = {
184
+ module: {
185
+ rules: [
186
+ {
187
+ test: /\.less$/i,
188
+ use: [
189
+ "style-loader",
190
+ "css-loader",
191
+ {
192
+ loader: "less-loader",
193
+ options: {
194
+ additionalData: (content, loaderContext) => {
195
+ // More information about available properties https://webpack.js.org/api/loaders/
196
+ const { resourcePath, rootContext } = loaderContext;
197
+ const relativePath = path.relative(rootContext, resourcePath);
198
+
199
+ if (relativePath === "styles/foo.less") {
200
+ return "@value: 100px;" + content;
201
+ }
202
+
203
+ return "@value: 200px;" + content;
204
+ },
205
+ },
206
+ },
207
+ ],
208
+ },
209
+ ],
210
+ },
211
+ };
212
+ ```
213
+
214
+ ##### Async
215
+
216
+ ```js
217
+ module.exports = {
218
+ module: {
219
+ rules: [
220
+ {
221
+ test: /\.less$/i,
222
+ use: [
223
+ "style-loader",
224
+ "css-loader",
225
+ {
226
+ loader: "less-loader",
227
+ options: {
228
+ additionalData: async (content, loaderContext) => {
229
+ // More information about available properties https://webpack.js.org/api/loaders/
230
+ const { resourcePath, rootContext } = loaderContext;
231
+ const relativePath = path.relative(rootContext, resourcePath);
232
+
233
+ if (relativePath === "styles/foo.less") {
234
+ return "@value: 100px;" + content;
235
+ }
236
+
237
+ return "@value: 200px;" + content;
238
+ },
239
+ },
240
+ },
241
+ ],
242
+ },
243
+ ],
244
+ },
245
+ };
246
+ ```
247
+
248
+ ### `sourceMap`
249
+
250
+ Type: `Boolean`
251
+ Default: depends on the `compiler.devtool` value
252
+
253
+ By default generation of source maps depends on the [`devtool`](https://webpack.js.org/configuration/devtool/) option. All values enable source map generation except `eval` and `false` value.
254
+
255
+ **webpack.config.js**
256
+
257
+ ```js
258
+ module.exports = {
259
+ module: {
260
+ rules: [
261
+ {
262
+ test: /\.less$/i,
263
+ use: [
264
+ "style-loader",
265
+ {
266
+ loader: "css-loader",
267
+ options: {
268
+ sourceMap: true,
269
+ },
270
+ },
271
+ {
272
+ loader: "less-loader",
273
+ options: {
274
+ sourceMap: true,
275
+ },
276
+ },
277
+ ],
278
+ },
279
+ ],
280
+ },
281
+ };
282
+ ```
283
+
284
+ ### `webpackImporter`
285
+
286
+ Type: `Boolean`
287
+ Default: `true`
288
+
289
+ Enables/Disables the default `webpack` importer.
290
+
291
+ This can improve performance in some cases. Use it with caution because aliases and `@import` at-rules starting with `~` will not work.
292
+
293
+ **webpack.config.js**
294
+
295
+ ```js
296
+ module.exports = {
297
+ module: {
298
+ rules: [
299
+ {
300
+ test: /\.less$/i,
301
+ use: [
302
+ "style-loader",
303
+ "css-loader",
304
+ {
305
+ loader: "less-loader",
306
+ options: {
307
+ webpackImporter: false,
308
+ },
309
+ },
310
+ ],
311
+ },
312
+ ],
313
+ },
314
+ };
315
+ ```
316
+
317
+ ### `implementation`
318
+
319
+ Type: `Object | String`
320
+
321
+ > ⚠ less-loader compatible with Less 3 and 4 versions
322
+
323
+ The special `implementation` option determines which implementation of Less to use. Overrides the locally installed `peerDependency` version of `less`.
324
+
325
+ **This option is only really useful for downstream tooling authors to ease the Less 3-to-4 transition.**
326
+
327
+ #### Object
328
+
329
+ **webpack.config.js**
330
+
331
+ ```js
332
+ module.exports = {
333
+ module: {
334
+ rules: [
335
+ {
336
+ test: /\.less$/i,
337
+ use: [
338
+ "style-loader",
339
+ "css-loader",
340
+ {
341
+ loader: "less-loader",
342
+ options: {
343
+ implementation: require("less"),
344
+ },
345
+ },
346
+ ],
347
+ },
348
+ ],
349
+ },
350
+ };
351
+ ```
352
+
353
+ #### String
354
+
355
+ **webpack.config.js**
356
+
357
+ ```js
358
+ module.exports = {
359
+ module: {
360
+ rules: [
361
+ {
362
+ test: /\.less$/i,
363
+ use: [
364
+ "style-loader",
365
+ "css-loader",
366
+ {
367
+ loader: "less-loader",
368
+ options: {
369
+ implementation: require.resolve("less"),
370
+ },
371
+ },
372
+ ],
373
+ },
374
+ ],
375
+ },
376
+ };
377
+ ```
378
+
379
+ ## Examples
380
+
381
+ ### Normal usage
382
+
383
+ Chain the `less-loader` with the [`css-loader`](https://github.com/webpack-contrib/css-loader) and the [`style-loader`](https://github.com/webpack-contrib/style-loader) to immediately apply all styles to the DOM.
384
+
385
+ **webpack.config.js**
386
+
387
+ ```js
388
+ module.exports = {
389
+ module: {
390
+ rules: [
391
+ {
392
+ test: /\.less$/i,
393
+ use: [
394
+ {
395
+ loader: "style-loader", // creates style nodes from JS strings
396
+ },
397
+ {
398
+ loader: "css-loader", // translates CSS into CommonJS
399
+ },
400
+ {
401
+ loader: "less-loader", // compiles Less to CSS
402
+ },
403
+ ],
404
+ },
405
+ ],
406
+ },
407
+ };
408
+ ```
409
+
410
+ Unfortunately, Less doesn't map all options 1-by-1 to camelCase. When in doubt, [check their executable](https://github.com/less/less.js/blob/3.x/bin/lessc) and search for the dash-case option.
411
+
412
+ ### Source maps
413
+
414
+ To enable sourcemaps for CSS, you'll need to pass the `sourceMap` property in the loader's options. If this is not passed, the loader will respect the setting for webpack source maps, set in `devtool`.
415
+
416
+ **webpack.config.js**
417
+
418
+ ```js
419
+ module.exports = {
420
+ devtool: "source-map", // any "source-map"-like devtool is possible
421
+ module: {
422
+ rules: [
423
+ {
424
+ test: /\.less$/i,
425
+ use: [
426
+ "style-loader",
427
+ {
428
+ loader: "css-loader",
429
+ options: {
430
+ sourceMap: true,
431
+ },
432
+ },
433
+ {
434
+ loader: "less-loader",
435
+ options: {
436
+ sourceMap: true,
437
+ },
438
+ },
439
+ ],
440
+ },
441
+ ],
442
+ },
443
+ };
444
+ ```
445
+
446
+ If you want to edit the original Less files inside Chrome, [there's a good blog post](https://medium.com/@toolmantim/getting-started-with-css-sourcemaps-and-in-browser-sass-editing-b4daab987fb0). The blog post is about Sass but it also works for Less.
447
+
448
+ ### In production
449
+
450
+ Usually, it's recommended to extract the style sheets into a dedicated file in production using the [MiniCssExtractPlugin](https://github.com/webpack-contrib/mini-css-extract-plugin). This way your styles are not dependent on JavaScript.
451
+
452
+ ### Imports
453
+
454
+ First we try to use built-in `less` resolve logic, then `webpack` resolve logic (aliases and `~`).
455
+
456
+ #### Webpack Resolver
457
+
458
+ `webpack` provides an [advanced mechanism to resolve files](https://webpack.js.org/configuration/resolve/).
459
+ `less-loader` applies a Less plugin that passes all queries to the webpack resolver if `less` could not resolve `@import`.
460
+ Thus you can import your Less modules from `node_modules`.
461
+
462
+ ```css
463
+ @import "bootstrap/less/bootstrap";
464
+ ```
465
+
466
+ Using `~` is deprecated and can be removed from your code (**we recommend it**), but we still support it for historical reasons.
467
+ Why you can removed it? The loader will first try to resolve `@import` as relative, if it cannot be resolved, the loader will try to resolve `@import` inside [`node_modules`](https://webpack.js.org/configuration/resolve/#resolve-modules).
468
+ Just prepend them with a `~` which tells webpack to look up the [`modules`](https://webpack.js.org/configuration/resolve/#resolve-modules).
469
+
470
+ ```css
471
+ @import "~bootstrap/less/bootstrap";
472
+ ```
473
+
474
+ Default resolver options can be modified by [`resolve.byDependency`](https://webpack.js.org/configuration/resolve/#resolvebydependency):
475
+
476
+ **webpack.config.js**
477
+
478
+ ```js
479
+ module.exports = {
480
+ devtool: "source-map", // any "source-map"-like devtool is possible
481
+ module: {
482
+ rules: [
483
+ {
484
+ test: /\.less$/i,
485
+ use: ["style-loader", "css-loader", "less-loader"],
486
+ },
487
+ ],
488
+ },
489
+ resolve: {
490
+ byDependency: {
491
+ // More options can be found here https://webpack.js.org/configuration/resolve/
492
+ less: {
493
+ mainFiles: ["custom"],
494
+ },
495
+ },
496
+ },
497
+ };
498
+ ```
499
+
500
+ It's important to only prepend it with `~`, because `~/` resolves to the home-directory. webpack needs to distinguish between `bootstrap` and `~bootstrap`, because CSS and Less files have no special syntax for importing relative files. Writing `@import "file"` is the same as `@import "./file";`
501
+
502
+ #### Less Resolver
503
+
504
+ If you specify the `paths` option, modules will be searched in the given `paths`. This is `less` default behavior. `paths` should be an array with absolute paths:
505
+
506
+ **webpack.config.js**
507
+
508
+ ```js
509
+ module.exports = {
510
+ module: {
511
+ rules: [
512
+ {
513
+ test: /\.less$/i,
514
+ use: [
515
+ {
516
+ loader: "style-loader",
517
+ },
518
+ {
519
+ loader: "css-loader",
520
+ },
521
+ {
522
+ loader: "less-loader",
523
+ options: {
524
+ lessOptions: {
525
+ paths: [path.resolve(__dirname, "node_modules")],
526
+ },
527
+ },
528
+ },
529
+ ],
530
+ },
531
+ ],
532
+ },
533
+ };
534
+ ```
535
+
536
+ ### Plugins
537
+
538
+ In order to use [plugins](http://lesscss.org/usage/#plugins), simply set the `plugins` option like this:
539
+
540
+ **webpack.config.js**
541
+
542
+ ```js
543
+ const CleanCSSPlugin = require('less-plugin-clean-css');
544
+
545
+ module.exports = {
546
+ ...
547
+ {
548
+ loader: 'less-loader',
549
+ options: {
550
+ lessOptions: {
551
+ plugins: [
552
+ new CleanCSSPlugin({ advanced: true }),
553
+ ],
554
+ },
555
+ },
556
+ },
557
+ ...
558
+ };
559
+ ```
560
+
561
+ > ℹ️ Access to the [loader context](https://webpack.js.org/api/loaders/#the-loader-context) inside the custom plugin can be done using the `pluginManager.webpackLoaderContext` property.
562
+
563
+ ```js
564
+ module.exports = {
565
+ install: function (less, pluginManager, functions) {
566
+ functions.add("pi", function () {
567
+ // Loader context is available in `pluginManager.webpackLoaderContext`
568
+
569
+ return Math.PI;
570
+ });
571
+ },
572
+ };
573
+ ```
574
+
575
+ ### Extracting style sheets
576
+
577
+ Bundling CSS with webpack has some nice advantages like referencing images and fonts with hashed urls or [hot module replacement](https://webpack.js.org/concepts/hot-module-replacement/) in development. In production, on the other hand, it's not a good idea to apply your style sheets depending on JS execution. Rendering may be delayed or even a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content) might be visible. Thus it's often still better to have them as separate files in your final production build.
578
+
579
+ There are two possibilities to extract a style sheet from the bundle:
580
+
581
+ - [`extract-loader`](https://github.com/peerigon/extract-loader) (simpler, but specialized on the css-loader's output)
582
+ - [MiniCssExtractPlugin](https://github.com/webpack-contrib/mini-css-extract-plugin) (more complex, but works in all use-cases)
583
+
584
+ ### CSS modules gotcha
585
+
586
+ There is a known problem with Less and [CSS modules](https://github.com/css-modules/css-modules) regarding relative file paths in `url(...)` statements. [See this issue for an explanation](https://github.com/webpack-contrib/less-loader/issues/109#issuecomment-253797335).
587
+
588
+ ## Contributing
589
+
590
+ Please take a moment to read our contributing guidelines if you haven't yet done so.
591
+
592
+ [CONTRIBUTING](./.github/CONTRIBUTING.md)
593
+
594
+ ## License
595
+
596
+ [MIT](./LICENSE)
597
+
598
+ [npm]: https://img.shields.io/npm/v/less-loader.svg
599
+ [npm-url]: https://npmjs.com/package/less-loader
600
+ [node]: https://img.shields.io/node/v/less-loader.svg
601
+ [node-url]: https://nodejs.org
602
+ [deps]: https://david-dm.org/webpack-contrib/less-loader.svg
603
+ [deps-url]: https://david-dm.org/webpack-contrib/less-loader
604
+ [tests]: https://github.com/webpack-contrib/less-loader/workflows/less-loader/badge.svg
605
+ [tests-url]: https://github.com/webpack-contrib/less-loader/actions
606
+ [cover]: https://codecov.io/gh/webpack-contrib/less-loader/branch/master/graph/badge.svg
607
+ [cover-url]: https://codecov.io/gh/webpack-contrib/less-loader
608
+ [chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
609
+ [chat-url]: https://gitter.im/webpack/webpack
610
+ [size]: https://packagephobia.now.sh/badge?p=less-loader
611
+ [size-url]: https://packagephobia.now.sh/result?p=less-loader
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ var _path = _interopRequireDefault(require("path"));
9
+
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+
12
+ class LessError extends Error {
13
+ constructor(error) {
14
+ super();
15
+ this.message = ["\n", ...LessError.getFileExcerptIfPossible(error), error.message.charAt(0).toUpperCase() + error.message.slice(1), error.filename ? ` Error in ${_path.default.normalize(error.filename)} (line ${error.line}, column ${error.column})` : ""].join("\n");
16
+ this.hideStack = true;
17
+ }
18
+
19
+ static getFileExcerptIfPossible(lessError) {
20
+ if (typeof lessError.extract === "undefined") {
21
+ return [];
22
+ }
23
+
24
+ const excerpt = lessError.extract.slice(0, 2);
25
+ const column = Math.max(lessError.column - 1, 0);
26
+
27
+ if (typeof excerpt[0] === "undefined") {
28
+ excerpt.shift();
29
+ }
30
+
31
+ excerpt.push(`${new Array(column).join(" ")}^`);
32
+ return excerpt;
33
+ }
34
+
35
+ }
36
+
37
+ var _default = LessError;
38
+ exports.default = _default;
package/dist/cjs.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+
3
+ module.exports = require("./index").default;
package/dist/index.js ADDED
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ var _path = _interopRequireDefault(require("path"));
9
+
10
+ var _options = _interopRequireDefault(require("./options.json"));
11
+
12
+ var _utils = require("./utils");
13
+
14
+ var _LessError = _interopRequireDefault(require("./LessError"));
15
+
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+
18
+ async function lessLoader(source) {
19
+ const options = this.getOptions(_options.default);
20
+ const callback = this.async();
21
+ const implementation = (0, _utils.getLessImplementation)(this, options.implementation);
22
+
23
+ if (!implementation) {
24
+ callback(new Error(`The Less implementation "${options.implementation}" not found`));
25
+ return;
26
+ }
27
+
28
+ const lessOptions = (0, _utils.getLessOptions)(this, options, implementation);
29
+ const useSourceMap = typeof options.sourceMap === "boolean" ? options.sourceMap : this.sourceMap;
30
+
31
+ if (useSourceMap) {
32
+ lessOptions.sourceMap = {
33
+ outputSourceFiles: true
34
+ };
35
+ }
36
+
37
+ let data = source;
38
+
39
+ if (typeof options.additionalData !== "undefined") {
40
+ data = typeof options.additionalData === "function" ? `${await options.additionalData(data, this)}` : `${options.additionalData}\n${data}`;
41
+ }
42
+
43
+ let result;
44
+
45
+ try {
46
+ result = await implementation.render(data, lessOptions);
47
+ } catch (error) {
48
+ if (error.filename) {
49
+ // `less` returns forward slashes on windows when `webpack` resolver return an absolute windows path in `WebpackFileManager`
50
+ // Ref: https://github.com/webpack-contrib/less-loader/issues/357
51
+ this.addDependency(_path.default.normalize(error.filename));
52
+ }
53
+
54
+ callback(new _LessError.default(error));
55
+ return;
56
+ }
57
+
58
+ delete lessOptions.pluginManager.webpackLoaderContext;
59
+ delete lessOptions.pluginManager;
60
+ const {
61
+ css,
62
+ imports
63
+ } = result;
64
+ imports.forEach(item => {
65
+ if ((0, _utils.isUnsupportedUrl)(item)) {
66
+ return;
67
+ } // `less` return forward slashes on windows when `webpack` resolver return an absolute windows path in `WebpackFileManager`
68
+ // Ref: https://github.com/webpack-contrib/less-loader/issues/357
69
+
70
+
71
+ const normalizedItem = _path.default.normalize(item); // Custom `importer` can return only `contents` so item will be relative
72
+
73
+
74
+ if (_path.default.isAbsolute(normalizedItem)) {
75
+ this.addDependency(normalizedItem);
76
+ }
77
+ });
78
+ let map = typeof result.map === "string" ? JSON.parse(result.map) : result.map;
79
+
80
+ if (map && useSourceMap) {
81
+ map = (0, _utils.normalizeSourceMap)(map, this.rootContext);
82
+ }
83
+
84
+ callback(null, css, map);
85
+ }
86
+
87
+ var _default = lessLoader;
88
+ exports.default = _default;
@@ -0,0 +1,54 @@
1
+ {
2
+ "title": "Less Loader options",
3
+ "type": "object",
4
+ "properties": {
5
+ "lessOptions": {
6
+ "description": "Options to pass through to `Less`.",
7
+ "link": "https://github.com/webpack-contrib/less-loader#lessoptions",
8
+ "anyOf": [
9
+ {
10
+ "type": "object",
11
+ "additionalProperties": true
12
+ },
13
+ {
14
+ "instanceof": "Function"
15
+ }
16
+ ]
17
+ },
18
+ "additionalData": {
19
+ "description": "Prepends/Appends `Less` code to the actual entry file.",
20
+ "link": "https://github.com/webpack-contrib/less-loader#additionalData",
21
+ "anyOf": [
22
+ {
23
+ "type": "string"
24
+ },
25
+ {
26
+ "instanceof": "Function"
27
+ }
28
+ ]
29
+ },
30
+ "sourceMap": {
31
+ "description": "Enables/Disables generation of source maps.",
32
+ "link": "https://github.com/webpack-contrib/less-loader#sourcemap",
33
+ "type": "boolean"
34
+ },
35
+ "webpackImporter": {
36
+ "description": "Enables/Disables default `webpack` importer.",
37
+ "link": "https://github.com/webpack-contrib/less-loader#webpackimporter",
38
+ "type": "boolean"
39
+ },
40
+ "implementation": {
41
+ "description": "The implementation of the `Less` to be used.",
42
+ "link": "https://github.com/webpack-contrib/less-loader#implementation",
43
+ "anyOf": [
44
+ {
45
+ "type": "string"
46
+ },
47
+ {
48
+ "type": "object"
49
+ }
50
+ ]
51
+ }
52
+ },
53
+ "additionalProperties": false
54
+ }
package/dist/utils.js ADDED
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getLessImplementation = getLessImplementation;
7
+ exports.getLessOptions = getLessOptions;
8
+ exports.isUnsupportedUrl = isUnsupportedUrl;
9
+ exports.normalizeSourceMap = normalizeSourceMap;
10
+
11
+ var _path = _interopRequireDefault(require("path"));
12
+
13
+ var _full = require("klona/full");
14
+
15
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
+
17
+ /* eslint-disable class-methods-use-this */
18
+ const trailingSlash = /[/\\]$/; // This somewhat changed in Less 3.x. Now the file name comes without the
19
+ // automatically added extension whereas the extension is passed in as `options.ext`.
20
+ // So, if the file name matches this regexp, we simply ignore the proposed extension.
21
+
22
+ const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/; // `[drive_letter]:\` + `\\[server]\[sharename]\`
23
+
24
+ const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i; // Examples:
25
+ // - ~package
26
+ // - ~package/
27
+ // - ~@org
28
+ // - ~@org/
29
+ // - ~@org/package
30
+ // - ~@org/package/
31
+
32
+ const IS_MODULE_IMPORT = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
33
+ const MODULE_REQUEST_REGEX = /^[^?]*~/;
34
+ /**
35
+ * Creates a Less plugin that uses webpack's resolving engine that is provided by the loaderContext.
36
+ *
37
+ * @param {LoaderContext} loaderContext
38
+ * @param {object} implementation
39
+ * @returns {LessPlugin}
40
+ */
41
+
42
+ function createWebpackLessPlugin(loaderContext, implementation) {
43
+ const resolve = loaderContext.getResolve({
44
+ dependencyType: "less",
45
+ conditionNames: ["less", "style"],
46
+ mainFields: ["less", "style", "main", "..."],
47
+ mainFiles: ["index", "..."],
48
+ extensions: [".less", ".css"],
49
+ preferRelative: true
50
+ });
51
+
52
+ class WebpackFileManager extends implementation.FileManager {
53
+ supports(filename) {
54
+ if (filename[0] === "/" || IS_NATIVE_WIN32_PATH.test(filename)) {
55
+ return true;
56
+ }
57
+
58
+ if (this.isPathAbsolute(filename)) {
59
+ return false;
60
+ }
61
+
62
+ return true;
63
+ } // Sync resolving is used at least by the `data-uri` function.
64
+ // This file manager doesn't know how to do it, so let's delegate it
65
+ // to the default file manager of Less.
66
+ // We could probably use loaderContext.resolveSync, but it's deprecated,
67
+ // see https://webpack.js.org/api/loaders/#this-resolvesync
68
+
69
+
70
+ supportsSync() {
71
+ return false;
72
+ }
73
+
74
+ async resolveFilename(filename, currentDirectory) {
75
+ // Less is giving us trailing slashes, but the context should have no trailing slash
76
+ const context = currentDirectory.replace(trailingSlash, "");
77
+ let request = filename; // A `~` makes the url an module
78
+
79
+ if (MODULE_REQUEST_REGEX.test(filename)) {
80
+ request = request.replace(MODULE_REQUEST_REGEX, "");
81
+ }
82
+
83
+ if (IS_MODULE_IMPORT.test(filename)) {
84
+ request = request[request.length - 1] === "/" ? request : `${request}/`;
85
+ }
86
+
87
+ return this.resolveRequests(context, [...new Set([request, filename])]);
88
+ }
89
+
90
+ async resolveRequests(context, possibleRequests) {
91
+ if (possibleRequests.length === 0) {
92
+ return Promise.reject();
93
+ }
94
+
95
+ let result;
96
+
97
+ try {
98
+ result = await resolve(context, possibleRequests[0]);
99
+ } catch (error) {
100
+ const [, ...tailPossibleRequests] = possibleRequests;
101
+
102
+ if (tailPossibleRequests.length === 0) {
103
+ throw error;
104
+ }
105
+
106
+ result = await this.resolveRequests(context, tailPossibleRequests);
107
+ }
108
+
109
+ return result;
110
+ }
111
+
112
+ async loadFile(filename, ...args) {
113
+ let result;
114
+
115
+ try {
116
+ if (IS_SPECIAL_MODULE_IMPORT.test(filename)) {
117
+ const error = new Error();
118
+ error.type = "Next";
119
+ throw error;
120
+ }
121
+
122
+ result = await super.loadFile(filename, ...args);
123
+ } catch (error) {
124
+ if (error.type !== "File" && error.type !== "Next") {
125
+ return Promise.reject(error);
126
+ }
127
+
128
+ try {
129
+ result = await this.resolveFilename(filename, ...args);
130
+ } catch (webpackResolveError) {
131
+ error.message = `Less resolver error:\n${error.message}\n\n` + `Webpack resolver error details:\n${webpackResolveError.details}\n\n` + `Webpack resolver error missing:\n${webpackResolveError.missing}\n\n`;
132
+ return Promise.reject(error);
133
+ }
134
+
135
+ loaderContext.addDependency(result);
136
+ return super.loadFile(result, ...args);
137
+ }
138
+
139
+ loaderContext.addDependency(_path.default.normalize(result.filename));
140
+ return result;
141
+ }
142
+
143
+ }
144
+
145
+ return {
146
+ install(lessInstance, pluginManager) {
147
+ pluginManager.addFileManager(new WebpackFileManager());
148
+ },
149
+
150
+ minVersion: [3, 0, 0]
151
+ };
152
+ }
153
+ /**
154
+ * Get the less options from the loader context and normalizes its values
155
+ *
156
+ * @param {object} loaderContext
157
+ * @param {object} loaderOptions
158
+ * @param {object} implementation
159
+ * @returns {Object}
160
+ */
161
+
162
+
163
+ function getLessOptions(loaderContext, loaderOptions, implementation) {
164
+ const options = (0, _full.klona)(typeof loaderOptions.lessOptions === "function" ? loaderOptions.lessOptions(loaderContext) || {} : loaderOptions.lessOptions || {});
165
+ const lessOptions = {
166
+ plugins: [],
167
+ relativeUrls: true,
168
+ // We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
169
+ filename: loaderContext.resourcePath,
170
+ ...options
171
+ };
172
+ const shouldUseWebpackImporter = typeof loaderOptions.webpackImporter === "boolean" ? loaderOptions.webpackImporter : true;
173
+
174
+ if (shouldUseWebpackImporter) {
175
+ lessOptions.plugins.unshift(createWebpackLessPlugin(loaderContext, implementation));
176
+ }
177
+
178
+ lessOptions.plugins.unshift({
179
+ install(lessProcessor, pluginManager) {
180
+ // eslint-disable-next-line no-param-reassign
181
+ pluginManager.webpackLoaderContext = loaderContext;
182
+ lessOptions.pluginManager = pluginManager;
183
+ }
184
+
185
+ });
186
+ return lessOptions;
187
+ }
188
+
189
+ function isUnsupportedUrl(url) {
190
+ // Is Windows path
191
+ if (IS_NATIVE_WIN32_PATH.test(url)) {
192
+ return false;
193
+ } // Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
194
+ // Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
195
+
196
+
197
+ return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url);
198
+ }
199
+
200
+ function normalizeSourceMap(map) {
201
+ const newMap = map; // map.file is an optional property that provides the output filename.
202
+ // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
203
+ // eslint-disable-next-line no-param-reassign
204
+
205
+ delete newMap.file; // eslint-disable-next-line no-param-reassign
206
+
207
+ newMap.sourceRoot = ""; // `less` returns POSIX paths, that's why we need to transform them back to native paths.
208
+ // eslint-disable-next-line no-param-reassign
209
+
210
+ newMap.sources = newMap.sources.map(source => _path.default.normalize(source));
211
+ return newMap;
212
+ }
213
+
214
+ function getLessImplementation(loaderContext, implementation) {
215
+ let resolvedImplementation = implementation;
216
+
217
+ if (!implementation || typeof implementation === "string") {
218
+ const lessImplPkg = implementation || "less";
219
+
220
+ try {
221
+ // eslint-disable-next-line import/no-dynamic-require, global-require
222
+ resolvedImplementation = require(lessImplPkg);
223
+ } catch (error) {
224
+ loaderContext.emitError(error); // eslint-disable-next-line consistent-return
225
+
226
+ return;
227
+ }
228
+ } // eslint-disable-next-line consistent-return
229
+
230
+
231
+ return resolvedImplementation;
232
+ }
package/package.json ADDED
@@ -0,0 +1,81 @@
1
+ {
2
+ "name": "less-loader",
3
+ "version": "10.1.0",
4
+ "description": "A Less loader for webpack. Compiles Less to CSS.",
5
+ "license": "MIT",
6
+ "repository": "webpack-contrib/less-loader",
7
+ "author": "Johannes Ewald @jhnns",
8
+ "homepage": "https://github.com/webpack-contrib/less-loader",
9
+ "bugs": "https://github.com/webpack-contrib/less-loader/issues",
10
+ "funding": {
11
+ "type": "opencollective",
12
+ "url": "https://opencollective.com/webpack"
13
+ },
14
+ "main": "dist/cjs.js",
15
+ "engines": {
16
+ "node": ">= 12.13.0"
17
+ },
18
+ "scripts": {
19
+ "start": "npm run build -- -w",
20
+ "clean": "del-cli dist",
21
+ "prebuild": "npm run clean",
22
+ "build": "cross-env NODE_ENV=production babel src -d dist --copy-files",
23
+ "commitlint": "commitlint --from=master",
24
+ "security": "npm audit --production",
25
+ "lint:prettier": "prettier --list-different .",
26
+ "lint:js": "eslint --cache .",
27
+ "lint": "npm-run-all -l -p \"lint:**\"",
28
+ "test:only": "cross-env NODE_ENV=test jest",
29
+ "test:watch": "npm run test:only -- --watch",
30
+ "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage",
31
+ "pretest": "npm run lint",
32
+ "test": "npm run test:coverage",
33
+ "prepare": "husky install && npm run build",
34
+ "release": "standard-version"
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "peerDependencies": {
40
+ "less": "^3.5.0 || ^4.0.0",
41
+ "webpack": "^5.0.0"
42
+ },
43
+ "dependencies": {
44
+ "klona": "^2.0.4"
45
+ },
46
+ "devDependencies": {
47
+ "@babel/cli": "^7.14.5",
48
+ "@babel/core": "^7.14.6",
49
+ "@babel/preset-env": "^7.14.7",
50
+ "@commitlint/cli": "^13.1.0",
51
+ "@commitlint/config-conventional": "^13.1.0",
52
+ "@webpack-contrib/eslint-config-webpack": "^3.0.0",
53
+ "babel-jest": "^27.0.6",
54
+ "cross-env": "^7.0.3",
55
+ "del": "^6.0.0",
56
+ "del-cli": "^4.0.1",
57
+ "eslint": "^7.30.0",
58
+ "eslint-config-prettier": "^8.3.0",
59
+ "eslint-plugin-import": "^2.24.1",
60
+ "husky": "^7.0.1",
61
+ "jest": "^27.0.6",
62
+ "less": "^4.1.1",
63
+ "less-plugin-glob": "^3.0.0",
64
+ "lint-staged": "^11.0.1",
65
+ "memfs": "^3.2.2",
66
+ "npm-run-all": "^4.1.5",
67
+ "prettier": "^2.3.2",
68
+ "standard-version": "^9.3.1",
69
+ "strip-ansi": "^7.0.0",
70
+ "webpack": "^5.51.1"
71
+ },
72
+ "keywords": [
73
+ "webpack",
74
+ "loader",
75
+ "less",
76
+ "lesscss",
77
+ "less.js",
78
+ "css",
79
+ "preprocessor"
80
+ ]
81
+ }