Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
loader-utils
Advanced tools
The loader-utils package provides utility functions for use with webpack loaders. It offers a variety of helper methods to make writing loaders easier and more standardized. These utilities include parsing query strings, hashing, getting options from loaders, and more.
getOptions
This function is used to parse the options passed to a loader. It simplifies the process of handling loader options within a webpack configuration.
const loaderUtils = require('loader-utils');
const options = loaderUtils.getOptions(this);
stringifyRequest
This method helps to convert a module request into a string that can be used inside of a loader. It's useful for ensuring that the request is correctly formatted and can be resolved by webpack.
const loaderUtils = require('loader-utils');
const stringifiedRequest = loaderUtils.stringifyRequest(this, require.resolve('./file.js'));
getHashDigest
This utility generates a hash digest of the given content. It's commonly used for cache busting or to generate unique identifiers for file contents.
const loaderUtils = require('loader-utils');
const hashDigest = loaderUtils.getHashDigest(Buffer.from('some content'), 'sha512', 'hex', 7);
interpolateName
This function allows for the creation of a custom filename based on placeholders and content. It's often used in file-loader and url-loader to generate names based on the file content.
const loaderUtils = require('loader-utils');
const interpolatedName = loaderUtils.interpolateName(this, '[name]_[hash].[ext]', { content: source });
Schema-utils validates options for webpack loaders and plugins against a JSON Schema. It is similar to loader-utils in that it helps with managing loader options, but it focuses on validation rather than utility functions.
File-loader resolves import/require() on a file into a url and emits the file into the output directory. It's similar to loader-utils' interpolateName feature but is a standalone loader that focuses on file handling.
Url-loader works like file-loader but can return a Data URL if the file is smaller than a byte limit. It shares some functionality with loader-utils, particularly in generating filenames and paths.
getLoaderConfig
Recommended way to retrieve the loader config:
// inside your loader
config = loaderUtils.getLoaderConfig(this, "myLoader");
Tries to read the loader config from the webpack.config.js
under the given property name ("myLoader"
in this case) and merges the result with the loader query. For example, if your webpack.config.js
had this property...
cheesecakeLoader: {
type: "delicious",
slices: 4
}
...and your loader was called with ?slices=8
, getLoaderConfig(this, "cheesecakeLoader")
would return
{
type: "delicious",
slices: 8
}
It is recommended that you use the camelCased loader name as your default config property name.
parseQuery
var query = loaderUtils.parseQuery(this.query);
assert(typeof query == "object");
if(query.flag)
// ...
null -> {}
? -> {}
?flag -> { flag: true }
?+flag -> { flag: true }
?-flag -> { flag: false }
?xyz=test -> { xyz: "test" }
?xyz[]=a -> { xyz: ["a"] }
?flag1&flag2 -> { flag1: true, flag2: true }
?+flag1,-flag2 -> { flag1: true, flag2: false }
?xyz[]=a,xyz[]=b -> { xyz: ["a", "b"] }
?a%2C%26b=c%2C%26d -> { "a,&b": "c,&d" }
?{json:5,data:{a:1}} -> { json: 5, data: { a: 1 } }
stringifyRequest
Turns a request into a string that can be used inside require()
or import
while avoiding absolute paths.
Use it instead of JSON.stringify(...)
if you're generating code inside a loader.
Why is this necessary? Since webpack calculates the hash before module paths are translated into module ids, we must avoid absolute paths to ensure consistent hashes across different compilations.
This function:
\
with /
if the request and the module are on the same hard driveJSON.stringify
to the resultloaderUtils.stringifyRequest(this, "./test.js");
// "\"./test.js\""
loaderUtils.stringifyRequest(this, ".\\test.js");
// "\"./test.js\""
loaderUtils.stringifyRequest(this, "test");
// "\"test\""
loaderUtils.stringifyRequest(this, "test/lib/index.js");
// "\"test/lib/index.js\""
loaderUtils.stringifyRequest(this, "otherLoader?andConfig!test?someConfig");
// "\"otherLoader?andConfig!test?someConfig\""
loaderUtils.stringifyRequest(this, require.resolve("test"));
// "\"../node_modules/some-loader/lib/test.js\""
loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
// "\"../../test.js\"" (on Windows, in case the module and the request are on the same drive)
loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
// "\"C:\\module\\test.js\"" (on Windows, in case the module and the request are on different drives)
loaderUtils.stringifyRequest(this, "\\\\network-drive\\test.js");
// "\"\\\\network-drive\\\\test.js\"" (on Windows, in case the module and the request are on different drives)
urlToRequest
Converts some resource URL to a webpack module request.
var url = "path/to/module.js";
var request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
Any URL containing a ~
will be interpreted as a module request. Anything after the ~
will be considered the request path.
var url = "~path/to/module.js";
var request = loaderUtils.urlToRequest(url); // "path/to/module.js"
URLs that are root-relative (start with /
) can be resolved relative to some arbitrary path by using the root
parameter:
var url = "/path/to/module.js";
var root = "./root";
var request = loaderUtils.urlToRequest(url, root); // "./root/path/to/module.js"
To convert a root-relative URL into a module URL, specify a root
value that starts with ~
:
var url = "/path/to/module.js";
var root = "~";
var request = loaderUtils.urlToRequest(url, root); // "path/to/module.js"
interpolateName
Interpolates a filename template using multiple placeholders and/or a regular expression.
The template and regular expression are set as query params called name
and regExp
on the current loader's context.
var interpolatedName = loaderUtils.interpolateName(loaderContext, name, options);
The following tokens are replaced in the name
parameter:
[ext]
the extension of the resource[name]
the basename of the resource[path]
the path of the resource relative to the context
query parameter or option.[folder]
the folder of the resource is in.[emoji]
a random emoji representation of options.content
[emoji:<length>]
same as above, but with a customizable number of emojis[hash]
the hash of options.content
(Buffer) (by default it's the hex digest of the md5 hash)[<hashType>:hash:<digestType>:<length>]
optionally one can configure
hashType
s, i. e. sha1
, md5
, sha256
, sha512
digestType
s, i. e. hex
, base26
, base32
, base36
, base49
, base52
, base58
, base62
, base64
length
the length in chars[N]
the N-th match obtained from matching the current file name against options.regExp
Examples
// loaderContext.resourcePath = "/app/js/javascript.js"
loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext]", { content: ... });
// => js/9473fdd0d880a43c21b7778d34872157.script.js
// loaderContext.resourcePath = "/app/page.html"
loaderUtils.interpolateName(loaderContext, "html-[hash:6].html", { content: ... });
// => html-9473fd.html
// loaderContext.resourcePath = "/app/flash.txt"
loaderUtils.interpolateName(loaderContext, "[hash]", { content: ... });
// => c31e9820c001c9c4a86bce33ce43b679
// loaderContext.resourcePath = "/app/img/image.gif"
loaderUtils.interpolateName(loaderContext, "[emoji]", { content: ... });
// => 👍
// loaderContext.resourcePath = "/app/img/image.gif"
loaderUtils.interpolateName(loaderContext, "[emoji:4]", { content: ... });
// => 🙍🏢📤🐝
// loaderContext.resourcePath = "/app/img/image.png"
loaderUtils.interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: ... });
// => 2BKDTjl.png
// use sha512 hash instead of md5 and with only 7 chars of base64
// loaderContext.resourcePath = "/app/img/myself.png"
// loaderContext.query.name =
loaderUtils.interpolateName(loaderContext, "picture.png");
// => picture.png
// loaderContext.resourcePath = "/app/dir/file.png"
loaderUtils.interpolateName(loaderContext, "[path][name].[ext]?[hash]", { content: ... });
// => /app/dir/file.png?9473fdd0d880a43c21b7778d34872157
// loaderContext.resourcePath = "/app/js/page-home.js"
loaderUtils.interpolateName(loaderContext, "script-[1].[ext]", { regExp: "page-(.*)\\.js", content: ... });
// => script-home.js
getHashDigest
var digestString = loaderUtils.getHashDigest(buffer, hashType, digestType, maxLength);
buffer
the content that should be hashedhashType
one of sha1
, md5
, sha256
, sha512
or any other node.js supported hash typedigestType
one of hex
, base26
, base32
, base36
, base49
, base52
, base58
, base62
, base64
maxLength
the maximum length in charsFAQs
utils for webpack loaders
We found that loader-utils demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.