less-loader 12.3.3 → 13.0.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/README.md +2 -2
- package/dist/{index.js → cjs/index.js} +50 -15
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/utils.js +387 -0
- package/dist/esm/index.js +134 -0
- package/dist/esm/options.json +67 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/utils.js +378 -0
- package/package.json +50 -34
- package/types/index.d.ts +21 -0
- package/types/utils.d.ts +112 -0
- package/dist/cjs.js +0 -3
- package/dist/utils.js +0 -216
- /package/dist/{options.json → cjs/options.json} +0 -0
package/README.md
CHANGED
|
@@ -429,7 +429,7 @@ Type:
|
|
|
429
429
|
type lessLogAsWarnOrErr = boolean;
|
|
430
430
|
```
|
|
431
431
|
|
|
432
|
-
Default: `
|
|
432
|
+
Default: `true`
|
|
433
433
|
|
|
434
434
|
`Less` warnings and errors will be treated as webpack warnings and errors, instead of being logged silently.
|
|
435
435
|
|
|
@@ -441,7 +441,7 @@ div {
|
|
|
441
441
|
}
|
|
442
442
|
```
|
|
443
443
|
|
|
444
|
-
If `lessLogAsWarnOrErr` is set to `false` it will be just a log and webpack will compile successfully, but if you set this option to `true` webpack will compile fail with a warning(or error), and can break the build if configured accordingly.
|
|
444
|
+
If `lessLogAsWarnOrErr` is set to `false` it will be just a log and webpack will compile successfully, but if you leave the default value (or set this option to `true`) webpack will compile fail with a warning(or error), and can break the build if configured accordingly.
|
|
445
445
|
|
|
446
446
|
**webpack.config.js**
|
|
447
447
|
|
|
@@ -6,79 +6,113 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.default = void 0;
|
|
7
7
|
var _nodePath = _interopRequireDefault(require("node:path"));
|
|
8
8
|
var _options = _interopRequireDefault(require("./options.json"));
|
|
9
|
-
var _utils = require("./utils");
|
|
9
|
+
var _utils = require("./utils.js");
|
|
10
10
|
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/** @typedef {import("webpack").LoaderContext<LoaderOptions>} LoaderContext */
|
|
12
|
+
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
|
|
13
|
+
/** @typedef {import("./utils.js").LoaderOptions} LoaderOptions */
|
|
14
|
+
/** @typedef {import("./utils.js").LessError} LessError */
|
|
15
|
+
/** @typedef {import("./utils.js").SourceMap} SourceMap */
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Webpack loader that compiles Less to CSS.
|
|
19
|
+
* @this {LoaderContext}
|
|
20
|
+
* @param {string} content content
|
|
21
|
+
* @returns {Promise<void>} loader result
|
|
22
|
+
*/
|
|
23
|
+
async function lessLoader(content) {
|
|
24
|
+
const options = this.getOptions(/** @type {Schema} */_options.default);
|
|
13
25
|
const callback = this.async();
|
|
14
26
|
let implementation;
|
|
15
27
|
try {
|
|
16
|
-
implementation = (0, _utils.getLessImplementation)(this, options.implementation);
|
|
28
|
+
implementation = await (0, _utils.getLessImplementation)(this, options.implementation);
|
|
17
29
|
} catch (error) {
|
|
18
|
-
callback(error);
|
|
30
|
+
callback(/** @type {Error} */error);
|
|
19
31
|
return;
|
|
20
32
|
}
|
|
21
33
|
if (!implementation) {
|
|
22
34
|
callback(new Error(`The Less implementation "${options.implementation}" not found`));
|
|
23
35
|
return;
|
|
24
36
|
}
|
|
25
|
-
const
|
|
37
|
+
const {
|
|
38
|
+
lessOptions,
|
|
39
|
+
pendingDependencyTasks
|
|
40
|
+
} = (0, _utils.getLessOptions)(this, options, implementation);
|
|
26
41
|
const useSourceMap = typeof options.sourceMap === "boolean" ? options.sourceMap : this.sourceMap;
|
|
27
42
|
if (useSourceMap) {
|
|
28
43
|
lessOptions.sourceMap = {
|
|
29
44
|
sourceMapBasepath: "",
|
|
30
45
|
outputSourceFiles: true,
|
|
46
|
+
// @ts-expect-error bad types
|
|
31
47
|
disableSourcemapAnnotation: true
|
|
32
48
|
};
|
|
33
49
|
}
|
|
34
|
-
let data =
|
|
50
|
+
let data = content;
|
|
35
51
|
if (typeof options.additionalData !== "undefined") {
|
|
36
52
|
data = typeof options.additionalData === "function" ? `${await options.additionalData(data, this)}` : `${options.additionalData}\n${data}`;
|
|
37
53
|
}
|
|
38
54
|
const logger = this.getLogger("less-loader");
|
|
39
55
|
const loaderContext = this;
|
|
56
|
+
const lessLogAsWarnOrErr = options.lessLogAsWarnOrErr !== false;
|
|
40
57
|
const loggerListener = {
|
|
58
|
+
/** @param {string} message message */
|
|
41
59
|
error(message) {
|
|
42
|
-
|
|
43
|
-
if (options.lessLogAsWarnOrErr) {
|
|
60
|
+
if (lessLogAsWarnOrErr) {
|
|
44
61
|
loaderContext.emitError(new Error(message));
|
|
45
62
|
} else {
|
|
46
63
|
logger.error(message);
|
|
47
64
|
}
|
|
48
65
|
},
|
|
66
|
+
/** @param {string} message message */
|
|
49
67
|
warn(message) {
|
|
50
|
-
|
|
51
|
-
if (options.lessLogAsWarnOrErr) {
|
|
68
|
+
if (lessLogAsWarnOrErr) {
|
|
52
69
|
loaderContext.emitWarning(new Error(message));
|
|
53
70
|
} else {
|
|
54
71
|
logger.warn(message);
|
|
55
72
|
}
|
|
56
73
|
},
|
|
74
|
+
/** @param {string} message message */
|
|
57
75
|
info(message) {
|
|
58
76
|
logger.log(message);
|
|
59
77
|
},
|
|
78
|
+
/** @param {string} message message */
|
|
60
79
|
debug(message) {
|
|
61
80
|
logger.debug(message);
|
|
62
81
|
}
|
|
63
82
|
};
|
|
83
|
+
|
|
84
|
+
// @ts-expect-error bad types
|
|
64
85
|
implementation.logger.addListener(loggerListener);
|
|
65
86
|
let result;
|
|
66
87
|
try {
|
|
67
88
|
result = await implementation.render(data, lessOptions);
|
|
68
89
|
} catch (error) {
|
|
69
|
-
|
|
90
|
+
const lessError = /** @type {LessError} */error;
|
|
91
|
+
if (lessError.filename) {
|
|
70
92
|
// `less` returns forward slashes on windows when `webpack` resolver return an absolute windows path in `WebpackFileManager`
|
|
71
93
|
// Ref: https://github.com/webpack/less-loader/issues/357
|
|
72
|
-
this.addDependency(_nodePath.default.normalize(
|
|
94
|
+
this.addDependency(_nodePath.default.normalize(lessError.filename));
|
|
73
95
|
}
|
|
74
|
-
|
|
96
|
+
|
|
97
|
+
// Wait for any pending sync-load dependency tracking so the failed
|
|
98
|
+
// build still snapshots the files it touched.
|
|
99
|
+
await Promise.all(pendingDependencyTasks);
|
|
100
|
+
callback((0, _utils.errorFactory)(lessError));
|
|
75
101
|
return;
|
|
76
102
|
} finally {
|
|
77
103
|
// Fix memory leaks in `less`
|
|
104
|
+
// @ts-expect-error bad types
|
|
78
105
|
implementation.logger.removeListener(loggerListener);
|
|
106
|
+
|
|
107
|
+
// @ts-expect-error we need it to reset loader context
|
|
79
108
|
delete lessOptions.pluginManager.webpackLoaderContext;
|
|
109
|
+
// @ts-expect-error we need it to reset loader context
|
|
80
110
|
delete lessOptions.pluginManager;
|
|
81
111
|
}
|
|
112
|
+
|
|
113
|
+
// Ensure dependencies for any synchronously loaded resources (e.g.
|
|
114
|
+
// `data-uri()`, `@plugin`) are tracked before the loader completes.
|
|
115
|
+
await Promise.all(pendingDependencyTasks);
|
|
82
116
|
const {
|
|
83
117
|
css,
|
|
84
118
|
imports
|
|
@@ -103,4 +137,5 @@ async function lessLoader(source) {
|
|
|
103
137
|
}
|
|
104
138
|
callback(null, css, map);
|
|
105
139
|
}
|
|
106
|
-
var _default = exports.default = lessLoader;
|
|
140
|
+
var _default = exports.default = lessLoader;module.exports = exports.default;
|
|
141
|
+
module.exports.default = exports.default;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.errorFactory = errorFactory;
|
|
7
|
+
exports.getLessImplementation = getLessImplementation;
|
|
8
|
+
exports.getLessOptions = getLessOptions;
|
|
9
|
+
exports.isUnsupportedUrl = isUnsupportedUrl;
|
|
10
|
+
exports.normalizeSourceMap = normalizeSourceMap;
|
|
11
|
+
var _nodePath = _interopRequireDefault(require("node:path"));
|
|
12
|
+
var _nodeUrl = _interopRequireDefault(require("node:url"));
|
|
13
|
+
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
14
|
+
/** @typedef {import("webpack").LoaderContext<LoaderOptions>} LoaderContext */
|
|
15
|
+
/** @typedef {import("less")} Less */
|
|
16
|
+
|
|
17
|
+
/** @typedef {Parameters<Less["render"]>[1]} LessOptions */
|
|
18
|
+
/** @typedef {NonNullable<LessOptions["plugins"]>[number]} LessPlugin */
|
|
19
|
+
/** @typedef {Less["FileManager"]} LessFileManager */
|
|
20
|
+
/** @typedef {InstanceType<Less["PluginManager"]>} PluginManager */
|
|
21
|
+
/** @typedef {InstanceType<LessFileManager>} LessFileManagerInstance */
|
|
22
|
+
/** @typedef {Parameters<InstanceType<LessFileManager>["loadFile"]>[2]} LoadFileOptions */
|
|
23
|
+
/** @typedef {Parameters<InstanceType<LessFileManager>["loadFile"]>[3]} Environment */
|
|
24
|
+
/** @typedef {Awaited<ReturnType<LessFileManagerInstance["loadFile"]>>} LoadFileResult */
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {object} LoaderOptions
|
|
28
|
+
* @property {LessOptions | ((loaderContext: LoaderContext) => LessOptions)=} lessOptions less options
|
|
29
|
+
* @property {string | ((source: string, loaderContext: LoaderContext) => string | Promise<string>)=} additionalData additional data
|
|
30
|
+
* @property {boolean=} sourceMap true when need to generate source map, otherwise false
|
|
31
|
+
* @property {boolean | "only"=} webpackImporter true when need to use webpack importer, otherwise false
|
|
32
|
+
* @property {string | Less=} implementation implementation
|
|
33
|
+
* @property {boolean=} lessLogAsWarnOrErr true when need to log less warnings and errors as webpack warnings and errors
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @typedef {object} SourceMap
|
|
38
|
+
* @property {string=} file file
|
|
39
|
+
* @property {string=} sourceRoot source root
|
|
40
|
+
* @property {string[]} sources sources
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @typedef {Error & { type?: string, filename?: string, line?: number, column?: number, extract?: string[] }} LessError
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
const trailingSlash = /[/\\]$/;
|
|
48
|
+
|
|
49
|
+
// This somewhat changed in Less 3.x. Now the file name comes without the
|
|
50
|
+
// automatically added extension whereas the extension is passed in as `options.ext`.
|
|
51
|
+
// So, if the file name matches this regexp, we simply ignore the proposed extension.
|
|
52
|
+
const IS_SPECIAL_MODULE_IMPORT = /^~[^/]+$/;
|
|
53
|
+
|
|
54
|
+
// `[drive_letter]:\` + `\\[server]\[share_name]\`
|
|
55
|
+
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
|
|
56
|
+
|
|
57
|
+
// Examples:
|
|
58
|
+
// - ~package
|
|
59
|
+
// - ~package/
|
|
60
|
+
// - ~@org
|
|
61
|
+
// - ~@org/
|
|
62
|
+
// - ~@org/package
|
|
63
|
+
// - ~@org/package/
|
|
64
|
+
const IS_MODULE_IMPORT = /^~([^/]+|[^/]+\/|@[^/]+[/][^/]+|@[^/]+\/?|@[^/]+[/][^/]+\/)$/;
|
|
65
|
+
const MODULE_REQUEST_REGEX = /^[^?]*~/;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Creates a Less plugin that uses webpack's resolving engine that is provided by the loaderContext.
|
|
69
|
+
* @param {LoaderContext} loaderContext loader context
|
|
70
|
+
* @param {Less} implementation implementation
|
|
71
|
+
* @param {Promise<void>[]} pendingDependencyTasks pending dependency tasks
|
|
72
|
+
* @returns {LessPlugin} less plugin
|
|
73
|
+
*/
|
|
74
|
+
function createWebpackLessPlugin(loaderContext, implementation, pendingDependencyTasks) {
|
|
75
|
+
const lessOptions = /** @type {LoaderOptions} */
|
|
76
|
+
loaderContext.getOptions();
|
|
77
|
+
const resolve = loaderContext.getResolve({
|
|
78
|
+
dependencyType: "less",
|
|
79
|
+
conditionNames: ["less", "style", "..."],
|
|
80
|
+
mainFields: ["less", "style", "main", "..."],
|
|
81
|
+
mainFiles: ["index", "..."],
|
|
82
|
+
extensions: [".less", ".css"],
|
|
83
|
+
preferRelative: true
|
|
84
|
+
});
|
|
85
|
+
class WebpackFileManager extends implementation.FileManager {
|
|
86
|
+
/**
|
|
87
|
+
* @param {string} filename filename
|
|
88
|
+
* @returns {boolean} true when filename is supported, otherwise false
|
|
89
|
+
*/
|
|
90
|
+
supports(filename) {
|
|
91
|
+
if (filename[0] === "/" || IS_NATIVE_WIN32_PATH.test(filename)) {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
if (this.isPathAbsolute(filename)) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Sync loading is used by `data-uri()` and any custom Less function
|
|
101
|
+
// (including those installed via `@plugin`). Webpack doesn't expose a
|
|
102
|
+
// sync resolver, so we fulfil the sync read by delegating to Less's
|
|
103
|
+
// default file manager (which can only handle native filesystem paths)
|
|
104
|
+
// and, in parallel, kick off an async webpack resolve so the loaded
|
|
105
|
+
// file is tracked as a webpack file dependency. Without this, webpack's
|
|
106
|
+
// persistent cache won't invalidate when a sync-loaded file changes.
|
|
107
|
+
// See https://github.com/webpack/less-loader/issues/492.
|
|
108
|
+
/**
|
|
109
|
+
* @returns {boolean} true when support sync, otherwise false
|
|
110
|
+
*/
|
|
111
|
+
supportsSync() {
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* @param {string} filename filename
|
|
117
|
+
* @param {string} currentDirectory current directory
|
|
118
|
+
* @param {LoadFileOptions} options options
|
|
119
|
+
* @param {Environment} environment environment
|
|
120
|
+
* @returns {LoadFileResult} loaded file
|
|
121
|
+
*/
|
|
122
|
+
loadFileSync(filename, currentDirectory, options, environment) {
|
|
123
|
+
// The default Less `loadFileSync` internally dispatches to
|
|
124
|
+
// `this.loadFile` with `options.syncImport = true`. Because we
|
|
125
|
+
// override `loadFile` (async), dynamic dispatch would land back in
|
|
126
|
+
// our async version and break the sync contract. Invoke the parent
|
|
127
|
+
// `loadFile` directly with the sync flag instead.
|
|
128
|
+
// @ts-expect-error bad types in less
|
|
129
|
+
const result = /** @type {LoadFileResult} */
|
|
130
|
+
super.loadFile(filename, currentDirectory, {
|
|
131
|
+
...options,
|
|
132
|
+
syncImport: true
|
|
133
|
+
}, environment);
|
|
134
|
+
if (result && result.filename) {
|
|
135
|
+
loaderContext.addDependency(_nodePath.default.normalize(_nodePath.default.isAbsolute(result.filename) ? result.filename : _nodePath.default.resolve(currentDirectory || ".", result.filename)));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Also try to resolve via webpack so aliases / custom resolvers can
|
|
139
|
+
// contribute dependencies. The resolved content is discarded - we
|
|
140
|
+
// only need the file path to track as a dependency.
|
|
141
|
+
pendingDependencyTasks.push(this.resolveFilename(filename, currentDirectory).then(resolved => {
|
|
142
|
+
const absoluteFilename = _nodePath.default.isAbsolute(resolved) ? resolved : _nodePath.default.resolve(".", resolved);
|
|
143
|
+
loaderContext.addDependency(_nodePath.default.normalize(absoluteFilename));
|
|
144
|
+
}).catch(() => {
|
|
145
|
+
// Webpack may legitimately fail to resolve paths that Less's
|
|
146
|
+
// default sync manager handled (e.g. node-style relative
|
|
147
|
+
// lookups). The sync result above is what Less consumes, so
|
|
148
|
+
// ignore the async failure.
|
|
149
|
+
}));
|
|
150
|
+
return result;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* @param {string} filename filename
|
|
155
|
+
* @param {string} currentDirectory current directory
|
|
156
|
+
* @returns {Promise<string>} resolved filename
|
|
157
|
+
*/
|
|
158
|
+
async resolveFilename(filename, currentDirectory) {
|
|
159
|
+
// Less is giving us trailing slashes, but the context should have no trailing slash
|
|
160
|
+
const context = currentDirectory.replace(trailingSlash, "");
|
|
161
|
+
let request = filename;
|
|
162
|
+
|
|
163
|
+
// A `~` makes the url an module
|
|
164
|
+
if (MODULE_REQUEST_REGEX.test(filename)) {
|
|
165
|
+
request = request.replace(MODULE_REQUEST_REGEX, "");
|
|
166
|
+
}
|
|
167
|
+
if (IS_MODULE_IMPORT.test(filename)) {
|
|
168
|
+
request = request[request.length - 1] === "/" ? request : `${request}/`;
|
|
169
|
+
}
|
|
170
|
+
return this.resolveRequests(context, [...new Set([request, filename])]);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @param {string} context context
|
|
175
|
+
* @param {string[]} possibleRequests possible requests
|
|
176
|
+
* @returns {Promise<string>} resolved requests
|
|
177
|
+
*/
|
|
178
|
+
async resolveRequests(context, possibleRequests) {
|
|
179
|
+
if (possibleRequests.length === 0) {
|
|
180
|
+
throw new Error("No possible requests to resolve");
|
|
181
|
+
}
|
|
182
|
+
let result;
|
|
183
|
+
try {
|
|
184
|
+
result = await resolve(context, possibleRequests[0]);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
const [, ...tailPossibleRequests] = possibleRequests;
|
|
187
|
+
if (tailPossibleRequests.length === 0) {
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
result = await this.resolveRequests(context, tailPossibleRequests);
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @param {string} filename filename
|
|
197
|
+
* @param {string} currentDirectory current directory
|
|
198
|
+
* @param {LoadFileOptions} options options
|
|
199
|
+
* @param {Environment} environment environment
|
|
200
|
+
* @returns {Promise<LoadFileResult>} loaded file
|
|
201
|
+
*/
|
|
202
|
+
async loadFile(filename, currentDirectory, options, environment) {
|
|
203
|
+
let result;
|
|
204
|
+
try {
|
|
205
|
+
if (IS_SPECIAL_MODULE_IMPORT.test(filename) || lessOptions.webpackImporter === "only") {
|
|
206
|
+
const error = /** @type {LessError} */new Error("Next");
|
|
207
|
+
error.type = "Next";
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
result = await super.loadFile(filename, currentDirectory, options, environment);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
const lessError = /** @type {LessError} */error;
|
|
213
|
+
if (lessError.type !== "File" && lessError.type !== "Next") {
|
|
214
|
+
throw error;
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
result = await this.resolveFilename(filename, currentDirectory);
|
|
218
|
+
} catch (err) {
|
|
219
|
+
lessError.message = `Less resolver error:\n${lessError.message}\n\n` + `Webpack resolver error details:\n${ /** @type {{ details: string }} */err.details}\n\n` + `Webpack resolver error missing:\n${ /** @type {{ missing: string }} */err.missing}\n\n`;
|
|
220
|
+
throw error;
|
|
221
|
+
}
|
|
222
|
+
loaderContext.addDependency(result);
|
|
223
|
+
return super.loadFile(result, currentDirectory, options, environment);
|
|
224
|
+
}
|
|
225
|
+
const absoluteFilename = _nodePath.default.isAbsolute(result.filename) ? result.filename : _nodePath.default.resolve(".", result.filename);
|
|
226
|
+
loaderContext.addDependency(_nodePath.default.normalize(absoluteFilename));
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
/**
|
|
232
|
+
* @param {Less} less less
|
|
233
|
+
* @param {PluginManager} pluginManager plugin manager
|
|
234
|
+
*/
|
|
235
|
+
install(less, pluginManager) {
|
|
236
|
+
pluginManager.addFileManager(new WebpackFileManager());
|
|
237
|
+
},
|
|
238
|
+
minVersion: [3, 0, 0]
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Get the `less` options from the loader context and normalizes its values
|
|
244
|
+
* @param {LoaderContext} loaderContext loader context
|
|
245
|
+
* @param {LoaderOptions} loaderOptions loader options
|
|
246
|
+
* @param {Less} implementation implementation
|
|
247
|
+
* @returns {{ lessOptions: LessOptions, pendingDependencyTasks: Promise<void>[] }} implementation and pending tasks
|
|
248
|
+
*/
|
|
249
|
+
function getLessOptions(loaderContext, loaderOptions, implementation) {
|
|
250
|
+
const options = typeof loaderOptions.lessOptions === "function" ? loaderOptions.lessOptions(loaderContext) || {} : loaderOptions.lessOptions || {};
|
|
251
|
+
|
|
252
|
+
/** @type {LessOptions} */
|
|
253
|
+
const lessOptions = {
|
|
254
|
+
// @ts-expect-error bad types
|
|
255
|
+
relativeUrls: true,
|
|
256
|
+
// We need to set the filename because otherwise our WebpackFileManager will receive an undefined path for the entry
|
|
257
|
+
filename: loaderContext.resourcePath,
|
|
258
|
+
...options
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// Collects async dependency-resolution promises kicked off from
|
|
262
|
+
// synchronous Less file loads (e.g. `data-uri()`, `@plugin`). The loader
|
|
263
|
+
// awaits these before completing so webpack's dependency snapshot is
|
|
264
|
+
// accurate.
|
|
265
|
+
/** @type {Promise<void>[]} */
|
|
266
|
+
const pendingDependencyTasks = [];
|
|
267
|
+
|
|
268
|
+
/** @type {LessPlugin[]} */
|
|
269
|
+
const plugins = [...(lessOptions.plugins || [])];
|
|
270
|
+
const shouldUseWebpackImporter = typeof loaderOptions.webpackImporter === "boolean" || loaderOptions.webpackImporter === "only" ? loaderOptions.webpackImporter : true;
|
|
271
|
+
if (shouldUseWebpackImporter) {
|
|
272
|
+
plugins.unshift(createWebpackLessPlugin(loaderContext, implementation, pendingDependencyTasks));
|
|
273
|
+
}
|
|
274
|
+
plugins.unshift({
|
|
275
|
+
/**
|
|
276
|
+
* @param {Less} less less
|
|
277
|
+
* @param {PluginManager} pluginManager plugin manager
|
|
278
|
+
*/
|
|
279
|
+
install(less, pluginManager) {
|
|
280
|
+
// @ts-expect-error to provide loader context into plugin
|
|
281
|
+
pluginManager.webpackLoaderContext = loaderContext;
|
|
282
|
+
// @ts-expect-error to reset it after execution
|
|
283
|
+
lessOptions.pluginManager = pluginManager;
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
lessOptions.plugins = plugins;
|
|
287
|
+
return {
|
|
288
|
+
lessOptions,
|
|
289
|
+
pendingDependencyTasks
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* @param {string} url url
|
|
295
|
+
* @returns {boolean} true when url is unsupported, otherwise false
|
|
296
|
+
*/
|
|
297
|
+
function isUnsupportedUrl(url) {
|
|
298
|
+
// Is Windows path
|
|
299
|
+
if (IS_NATIVE_WIN32_PATH.test(url)) {
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
|
|
304
|
+
// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
|
|
305
|
+
return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(url);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* @param {SourceMap} map map
|
|
310
|
+
* @returns {SourceMap} normalized source map
|
|
311
|
+
*/
|
|
312
|
+
function normalizeSourceMap(map) {
|
|
313
|
+
const newMap = map;
|
|
314
|
+
|
|
315
|
+
// map.file is an optional property that provides the output filename.
|
|
316
|
+
// Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
|
|
317
|
+
|
|
318
|
+
delete newMap.file;
|
|
319
|
+
newMap.sourceRoot = "";
|
|
320
|
+
|
|
321
|
+
// `less` returns POSIX paths, that's why we need to transform them back to native paths.
|
|
322
|
+
|
|
323
|
+
newMap.sources = newMap.sources.map(source => _nodePath.default.normalize(source));
|
|
324
|
+
return newMap;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* @param {string} specifier specifier
|
|
329
|
+
* @returns {string} resolved specifier
|
|
330
|
+
*/
|
|
331
|
+
function normalizeImportSpecifier(specifier) {
|
|
332
|
+
if (specifier.startsWith("file:")) {
|
|
333
|
+
return specifier;
|
|
334
|
+
}
|
|
335
|
+
if (_nodePath.default.isAbsolute(specifier)) {
|
|
336
|
+
return _nodeUrl.default.pathToFileURL(specifier).href;
|
|
337
|
+
}
|
|
338
|
+
return specifier;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* @param {LoaderContext} loaderContext loader context
|
|
343
|
+
* @param {string | Less | undefined} implementation implementation
|
|
344
|
+
* @returns {Promise<Less>} less implementation
|
|
345
|
+
*/
|
|
346
|
+
async function getLessImplementation(loaderContext, implementation) {
|
|
347
|
+
let resolvedImplementation = implementation;
|
|
348
|
+
if (!implementation || typeof implementation === "string") {
|
|
349
|
+
const lessImplPkg = implementation || "less";
|
|
350
|
+
const imported = await import(normalizeImportSpecifier(lessImplPkg));
|
|
351
|
+
resolvedImplementation = imported.default ?? imported;
|
|
352
|
+
}
|
|
353
|
+
return /** @type {Less} */resolvedImplementation;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* @param {LessError} error error
|
|
358
|
+
* @returns {string[]} file excerpt
|
|
359
|
+
*/
|
|
360
|
+
function getFileExcerptIfPossible(error) {
|
|
361
|
+
if (typeof error.extract === "undefined") {
|
|
362
|
+
return [];
|
|
363
|
+
}
|
|
364
|
+
const excerpt = error.extract.slice(0, 2);
|
|
365
|
+
const column = Math.max(/** @type {number} */error.column - 1, 0);
|
|
366
|
+
if (typeof excerpt[0] === "undefined") {
|
|
367
|
+
excerpt.shift();
|
|
368
|
+
}
|
|
369
|
+
excerpt.push(`${" ".repeat(column)}^`);
|
|
370
|
+
return excerpt;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* @param {LessError} error error
|
|
375
|
+
* @returns {Error} built error
|
|
376
|
+
*/
|
|
377
|
+
function errorFactory(error) {
|
|
378
|
+
const message = ["\n", ...getFileExcerptIfPossible(error), error.message.charAt(0).toUpperCase() + error.message.slice(1), error.filename ? ` Error in ${_nodePath.default.normalize(error.filename)} (line ${error.line}, column ${error.column})` : ""].join("\n");
|
|
379
|
+
const obj = /** @type {Error & { stack: string | null }} */
|
|
380
|
+
new Error(message, {
|
|
381
|
+
cause: error
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
// @ts-expect-error avoid extra stack for less
|
|
385
|
+
obj.stack = null;
|
|
386
|
+
return obj;
|
|
387
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import schema from "./options.json" with { type: "json" };
|
|
3
|
+
import { errorFactory, getLessImplementation, getLessOptions, isUnsupportedUrl, normalizeSourceMap } from "./utils.js";
|
|
4
|
+
|
|
5
|
+
/** @typedef {import("webpack").LoaderContext<LoaderOptions>} LoaderContext */
|
|
6
|
+
/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
|
|
7
|
+
/** @typedef {import("./utils.js").LoaderOptions} LoaderOptions */
|
|
8
|
+
/** @typedef {import("./utils.js").LessError} LessError */
|
|
9
|
+
/** @typedef {import("./utils.js").SourceMap} SourceMap */
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Webpack loader that compiles Less to CSS.
|
|
13
|
+
* @this {LoaderContext}
|
|
14
|
+
* @param {string} content content
|
|
15
|
+
* @returns {Promise<void>} loader result
|
|
16
|
+
*/
|
|
17
|
+
async function lessLoader(content) {
|
|
18
|
+
const options = this.getOptions(/** @type {Schema} */schema);
|
|
19
|
+
const callback = this.async();
|
|
20
|
+
let implementation;
|
|
21
|
+
try {
|
|
22
|
+
implementation = await getLessImplementation(this, options.implementation);
|
|
23
|
+
} catch (error) {
|
|
24
|
+
callback(/** @type {Error} */error);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (!implementation) {
|
|
28
|
+
callback(new Error(`The Less implementation "${options.implementation}" not found`));
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const {
|
|
32
|
+
lessOptions,
|
|
33
|
+
pendingDependencyTasks
|
|
34
|
+
} = getLessOptions(this, options, implementation);
|
|
35
|
+
const useSourceMap = typeof options.sourceMap === "boolean" ? options.sourceMap : this.sourceMap;
|
|
36
|
+
if (useSourceMap) {
|
|
37
|
+
lessOptions.sourceMap = {
|
|
38
|
+
sourceMapBasepath: "",
|
|
39
|
+
outputSourceFiles: true,
|
|
40
|
+
// @ts-expect-error bad types
|
|
41
|
+
disableSourcemapAnnotation: true
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
let data = content;
|
|
45
|
+
if (typeof options.additionalData !== "undefined") {
|
|
46
|
+
data = typeof options.additionalData === "function" ? `${await options.additionalData(data, this)}` : `${options.additionalData}\n${data}`;
|
|
47
|
+
}
|
|
48
|
+
const logger = this.getLogger("less-loader");
|
|
49
|
+
const loaderContext = this;
|
|
50
|
+
const lessLogAsWarnOrErr = options.lessLogAsWarnOrErr !== false;
|
|
51
|
+
const loggerListener = {
|
|
52
|
+
/** @param {string} message message */
|
|
53
|
+
error(message) {
|
|
54
|
+
if (lessLogAsWarnOrErr) {
|
|
55
|
+
loaderContext.emitError(new Error(message));
|
|
56
|
+
} else {
|
|
57
|
+
logger.error(message);
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
/** @param {string} message message */
|
|
61
|
+
warn(message) {
|
|
62
|
+
if (lessLogAsWarnOrErr) {
|
|
63
|
+
loaderContext.emitWarning(new Error(message));
|
|
64
|
+
} else {
|
|
65
|
+
logger.warn(message);
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
/** @param {string} message message */
|
|
69
|
+
info(message) {
|
|
70
|
+
logger.log(message);
|
|
71
|
+
},
|
|
72
|
+
/** @param {string} message message */
|
|
73
|
+
debug(message) {
|
|
74
|
+
logger.debug(message);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// @ts-expect-error bad types
|
|
79
|
+
implementation.logger.addListener(loggerListener);
|
|
80
|
+
let result;
|
|
81
|
+
try {
|
|
82
|
+
result = await implementation.render(data, lessOptions);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
const lessError = /** @type {LessError} */error;
|
|
85
|
+
if (lessError.filename) {
|
|
86
|
+
// `less` returns forward slashes on windows when `webpack` resolver return an absolute windows path in `WebpackFileManager`
|
|
87
|
+
// Ref: https://github.com/webpack/less-loader/issues/357
|
|
88
|
+
this.addDependency(path.normalize(lessError.filename));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Wait for any pending sync-load dependency tracking so the failed
|
|
92
|
+
// build still snapshots the files it touched.
|
|
93
|
+
await Promise.all(pendingDependencyTasks);
|
|
94
|
+
callback(errorFactory(lessError));
|
|
95
|
+
return;
|
|
96
|
+
} finally {
|
|
97
|
+
// Fix memory leaks in `less`
|
|
98
|
+
// @ts-expect-error bad types
|
|
99
|
+
implementation.logger.removeListener(loggerListener);
|
|
100
|
+
|
|
101
|
+
// @ts-expect-error we need it to reset loader context
|
|
102
|
+
delete lessOptions.pluginManager.webpackLoaderContext;
|
|
103
|
+
// @ts-expect-error we need it to reset loader context
|
|
104
|
+
delete lessOptions.pluginManager;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Ensure dependencies for any synchronously loaded resources (e.g.
|
|
108
|
+
// `data-uri()`, `@plugin`) are tracked before the loader completes.
|
|
109
|
+
await Promise.all(pendingDependencyTasks);
|
|
110
|
+
const {
|
|
111
|
+
css,
|
|
112
|
+
imports
|
|
113
|
+
} = result;
|
|
114
|
+
for (const item of imports) {
|
|
115
|
+
if (isUnsupportedUrl(item)) {
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// `less` return forward slashes on windows when `webpack` resolver return an absolute windows path in `WebpackFileManager`
|
|
120
|
+
// Ref: https://github.com/webpack/less-loader/issues/357
|
|
121
|
+
const normalizedItem = path.normalize(item);
|
|
122
|
+
|
|
123
|
+
// Custom `importer` can return only `contents` so item will be relative
|
|
124
|
+
if (path.isAbsolute(normalizedItem)) {
|
|
125
|
+
this.addDependency(normalizedItem);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
let map = typeof result.map === "string" ? JSON.parse(result.map) : result.map;
|
|
129
|
+
if (map && useSourceMap) {
|
|
130
|
+
map = normalizeSourceMap(map);
|
|
131
|
+
}
|
|
132
|
+
callback(null, css, map);
|
|
133
|
+
}
|
|
134
|
+
export default lessLoader;
|