Security News
New Python Packaging Proposal Aims to Solve Phantom Dependency Problem with SBOMs
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
magic-comments-loader
Advanced tools
Add webpack magic comments to your dynamic imports at build time.
magic-comments-loader
🪄Keep your source code clean, add magic comments to your dynamic import()
expressions at build time.
First install magic-comments-loader
:
npm install magic-comments-loader
Next add the loader to your webpack.config.js
file:
module: {
rules: [
{
test: /\.jsx?$/,
use: ['magic-comments-loader']
}
]
}
Then given a file.js with the following import:
const dynamicModule = await import('./path/to/module.js')
While running webpack
the dynamic import inside file.js becomes:
const dynamicModule = await import(/* webpackChunkName: "path-to-module" */ './path/to/module.js')
The webpackChunkName
comment is added by default when registering the loader. See the supported options to learn about configuring other magic comments.
verbose
mode
match
comments
[magicCommentName: string]: MagicCommentValue
see magic-comments
options for detailsverbose
type
boolean
default false
Prints console statements of the module filepath and updated import()
during the webpack build. Useful for debugging.
mode
type
'parser' | 'regexp'
default 'parser'
Sets how the loader finds dynamic import expressions in your source code, either using an ECMAScript parser, or a regular expression. Your mileage may vary when using 'regexp'
.
match
type
'module' | 'import'
default 'module'
Sets how globs are matched, either the module file path, or the import()
specifier.
comments
type
'ignore' | 'prepend' | 'append' | 'replace'
| (cmts: Array<{ start: number; end: number; text: string }>, magicComment: string) => string
default 'ignore'
Note, this option only considers block comments that precede the dynamic imports specifier, and any comments coming after are ignored and left intact.
Sets how dynamic imports with block comments are handled. If ignore
is used, then it will be skipped and no magic comments from your configuration will be applied. If replace
is used, then all found comments will be replaced with the magic comments. append
and prepend
add the magic comments before, or after the found comments, respectively. If a function is used it will be passed the found comments, and the magic comment string that is to be applied. The return value has the same effect as replace
.
Below are examples for some of the supported magic comments. Consult the loader specification for a comprehensive usage example.
Add webpackChunkName
magic comments to dynamic imports matching the provided glob(s), using the import path in kebab-case as the default chunk name. Glob matching is done using micromatch.
config
module: {
rules: [
{
test: /\.[jt]sx?$/,
use: {
loader: 'magic-comments-loader',
options: {
webpackChunkName: ['**/src/**/*.js']
}
}
}
]
}
src
import('./folder/module.js')
build
import(/* webpackChunkName: "folder-module" */ './folder/module.js')
To define a custom chunk name, use a function as the option value. Returning nothing, or a falsy value skips adding the comment.
config
module: {
rules: [
{
test: /\.[jt]sx?$/,
use: {
loader: 'magic-comments-loader',
options: {
webpackChunkName: (modulePath, importPath) => {
if (importPath.endsWith('module.js')) {
return 'custom-chunk-name'
}
}
}
}
}
]
}
src
import('./folder/module.js')
build
import(/* webpackChunkName: "custom-chunk-name" */ './folder/module.js')
Finally, using a CommentConfig
object you can change the chunk name to the import specifier's basename (instead of the full hyphenated path). This could potentially result in name collisions, so be mindful of import specifiers when activating. You could also achieve the same thing by using a function instead of options.basename
.
config
module: {
rules: [
{
test: /\.[jt]sx?$/,
use: {
loader: 'magic-comments-loader',
options: {
webpackChunkName: {
options: {
basename: true
}
}
}
}
}
]
}
src
import('./folder/module.js')
build
import(/* webpackChunkName: "module" */ './folder/module.js')
Most of the magic comments can be configured similarly, and all support configuration as a function with the signature (modulePath: string, importPath: string) => any
, albeit the return type is checked at runtime for compliance with the expected values. Check out the options for magic-comments
more details.
You can add multiple magic comments.
config
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'magic-comments-loader',
options: {
webpackChunkName: true,
webpackMode: 'lazy',
webpackFetchPriority: (modulePath, importPath) => {
if (importPath.includes('priority')) {
return 'high'
}
}
}
}
}
]
}
src
import('./priority/module.js')
build
import(/* webpackChunkName: "priority-module", webpackMode: "lazy", webpackFetchPriority: "high" */ './priority/module.js')
When using a CommentConfig
object, you can override the configuration passed in the options
key by defining overrides
. It is an array of objects that look like:
Array<{
files: string | string[];
options: CommentOptions;
}>
The files
and options
keys are both required, where the former is a glob string, or an array thereof, and the latter is the associated magic comment's CommentOptions
.
Here's a more complete example of how overrides can be applied:
config
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'magic-comments-loader',
options: {
match: 'import', // Now provided globs match against the import specifier
webpackChunkName: '*.json',
webpackMode: {
options: {
mode: 'lazy'
},
overrides: [
{
files: ['**/eager/**/*.js'],
options: {
mode: 'eager'
}
},
{
files: ['**/locales/**/*.json'],
options: {
mode: 'lazy-once'
}
}
]
}
}
}
}
]
}
src
const lang = 'es'
import('./folder/module.js')
import('./eager/module.js')
import(`./locales/${lang}.json`)
build
const lang = 'es'
import(/* webpackMode: "lazy" */ './folder/module.js')
import(/* webpackMode: "eager" */ './eager/module.js')
import(/* webpackChunkName: "locales-[request]", webpackMode: "lazy-once" */ `./locales/${lang}.json`)
You can also see the example for overrides in magic-comments
.
When using TypeScript or experimental ECMAScript features <= stage 3, i.e. non spec compliant, you must chain the appropriate loaders with magic-comments-loader
coming after.
For example, if your project source code is written in TypeScript, and you use babel-loader
to transpile and remove type annotations via @babel/preset-typescript
, while tsc
is used for type-checking only, chain loaders like this:
config
module: {
rules: [
{
test: /\.[jt]sx?$/,
// Webpack loader chains are processed in reverse order, i.e. last comes first.
use: [
'magic-comments-loader',
'babel-loader'
]
}
]
}
You would configure ts-loader
similarly, or any other loader that transpiles your source code into spec compliant ECMAScript.
FAQs
Add webpack magic comments to your dynamic imports at build time.
The npm package magic-comments-loader receives a total of 627 weekly downloads. As such, magic-comments-loader popularity was classified as not popular.
We found that magic-comments-loader demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 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
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
Security News
Socket CEO Feross Aboukhadijeh discusses open source security challenges, including zero-day attacks and supply chain risks, on the Cyber Security Council podcast.
Security News
Research
Socket researchers uncover how threat actors weaponize Out-of-Band Application Security Testing (OAST) techniques across the npm, PyPI, and RubyGems ecosystems to exfiltrate sensitive data.