5

I'm currently experimenting with the following strategy to dynamically load a json file from a path relative to my module :

  • If my code is bundled as a Webpack bundle, use import(filename.json)
  • In any other case, fall back to an AJAX call, with an absolute path

The following seems to work fine :

function parse (fileName, callback) {
  var path = "./relative/path/to/" + fileName + ".json";
  var cb = process.bind(this, fileName, callback);
  if (typeof webpackJsonp !== "undefined") { // <-- Test if run as Webpack bundle
    // Do dynamic import
  } else {
    // Do Ajax call
  }
}

However, I can't find any documentation on webpackJsonp, however, so I assume this is not part of Webpack's public API.

I also noticed that webpackJsonp is a function in 3.12 and an Object (inheriting from Array) in 4.28, indicating how fragile it is to rely on the presence, value or type of webpackJsonp.

Is there a (future-proof) reliable way test whether my code is being run as a Webpack bundle, using public API?

Basically, what should I replace typeof webpackJsonp !== "undefined" with, to achieve the same effect, but using public API?

Additionally, I'm also having some problems with getting the actual import to work in Webpack 4.28. See import() breaks in Angular 7.2.3 + Webpack 4.28 for that.

John Slegers
  • 45,213
  • 22
  • 199
  • 169

0 Answers0