next.js: with-polyfills: Dynamic import of polyfill causes chunk load error

Examples bug report

Example name

with-polyfills

Describe the bug

with-polyfills shows how to polyfill missing features prior to initialization of Next app. However, I would like to load polyfills only for the missing features using the dynamic import.

For example IntersectionObserver is supported widely in the latest versions of browsers, so it’s usually not necessary to load the intersection-observer polyfill. Thus I would like to import the polyfill only when the feature is missing like this:

// client/polyfills.js

async function loadPolyfills() {
  if (typeof window.IntersectionObserver === 'undefined') {
    await import('intersection-observer')
  }
}
export default loadPolyfills()

When I do that the application crashes when browser attempts to load the polyfill with the following error:

Unhandled Rejection (ChunkLoadError): Loading chunk 0 failed.
(error: http://localhost:3000/static/chunks/0.js)

Apparently Webpack points to the chunk in a wrong location, since the chunk is available in _next directory, i.e. http://localhost:3000/_next/static/chunks/0.js

To Reproduce

I have prepared a repository with reproduction of the issue. The feature detection is commented out to reproduce the behavior in any browser.

  1. Download or clone https://github.com/jnv/next-with-polyfills-dynamic-import
  2. Install dependencies with yarn
  3. Start application with yarn dev
  4. Go to http://localhost:3000/
  5. See the error

Expected behavior

Browser loads the chunk without error, before Next initialization.

Screenshots

Error in browser

System information

  • OS: macOS
  • Browser: does not apply
  • Version of Next.js: 9.0.2

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 34
  • Comments: 27 (7 by maintainers)

Most upvoted comments

I’d remove the word “polyfill” from this issue because it seems to just flat out happen for dynamic imports. I am still continually hit by this

Hi,

I experienced the same issue and fixed it inside custom Webpack configuration file by adding the following:

// One-time procedures to run
if (!isServer) {
	// For polyfills chunks to be correctly loaded
	config.output.publicPath = '/_next/';
}

This is quite a blocker for what I’m working on so I’m going to dive into the codebase and see if I can suggest a fix. Any time-saving recommendations of where to look appreciated!

@mulholio I’ve tried to find some leads in the codebase (e.g. references to _next/static/chunks directory etc.), but found only a few integration tests. Personally I’d start with build directory in the next package, and especially webpack-config. Creating an integration test from the example may be also helpful once you identify the source of this issue.