Saturday, 1 April 2017

How to define webpack dynamic context where node.js code try to find a filename with fallback?

I try to webpack a node.js module and stumbling on some code where we try to require a JSON file with a fallback to a file that will exist at all events. The following code is a hard nut for webpack.

var tryRequire = function(filename){
  var result = null;
  if (fs.existsSync(filename)){
    result = require(filename);
  }
  return result;
}

var getI18nStorage = function(culture){
  var cultureParts = culture.toLowerCase().split("-");
  var dir = path.join(__dirname, "../../i18n/address");
  var fn = cultureParts[0] + ".json";
  var filename = path.join(dir, fn);
  var storage = tryRequire(filename);
  if (!storage){
    fn = cultureParts[1] + ".json";
    filename = path.join(dir, fn);
    storage = tryRequire(filename);
    if (!storage){
      fn = "us.json";
      filename = path.join(dir, fn);
      storage = tryRequire(filename);
/*      if (!storage){
        console.log(culture, "nothing found");
        process.exit(1)
      }*/
    }
  }

  return storage;
}

Currently packing var c = getI18nStorage("en-GB"); results in !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; which is understandable :o)

I tried to learn from https://github.com/webpack/webpack/tree/master/examples/require.context but could not transfer the technique to my problem. I think I need to know 2 things:

  • How to manualy add requiered modules to webpack if they cannot be resolved programaticaly?
    • I tried to add context: path.join(__dirname, "../lib/i18n"), to webpack config but this does not include data to bundled output.
  • Is there a way to help webpack to understand this node.js filesystem strategy to try to find a required module?


via Stephan Ahlf

No comments:

Post a Comment