npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

magic-comments-loader

v2.1.2

Published

Add webpack magic comments to your dynamic imports at build time.

Downloads

4,565

Readme

magic-comments-loader 🪄

CI codecov NPM version

Keep your source code clean, add magic comments to your dynamic import() expressions at build time.

Getting Started

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.

Options

verbose

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 is only applied when mode is parser.

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 after, or before the found comments, respectively.

When 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. There is an example of using a function in the loader specification.

Examples

Below are examples for some of the supported magic comments. Consult the loader specification for a comprehensive usage example.

webpackChunkName

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.

Multiple

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')

Overrides

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.

TypeScript

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.