Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Webpack chunk url as string when using dynamic imports

With Webpack I can load a module like this:

import(moduleName).then(_ => {})

However I would only like to get the URL of the chunk, not actually load it. Is that possible?

like image 223
Matt Zeunert Avatar asked Nov 17 '22 19:11

Matt Zeunert


1 Answers

You can do this in Webpack 5 by re-using the Worker Plugin with module.parser.

// utils/chunk-url.js
export function ChunkUrl(url) { return url; }

Webpack config:

webpackConfig.module = {
  parser: {
    javascript: {
      worker: ["ChunkUrl from ~/utils/chunk-url", "..."]
    }
  }
}

Example usage:

import { ChunkUrl } from '~/utils/chunk-url';

// .../chunks/[hash].js
const ScriptUrl = new ChunkUrl(new URL('/path/to/file.js', import.meta.url)); 

The file will go through a child compiler like a dynamic import, but only the URL is returned.

like image 181
Alfredo Lopez Avatar answered Feb 23 '23 01:02

Alfredo Lopez