DanielSchaffer/webpack-babel-multi-target-plugin

[Discussion] Any thoughts about generates the true es6 ( aka not flattened ) modules?

Closed this issue · 1 comments

Great project! But I'm thinking further: What about generates unflattened modules?

  1. Parse the whole repo recursively, to build an import-map. Or transform import Xxx from 'some_module' into import Xxx from '/node_modules/some_module/index.js'.
  2. All files imported are still transformed using loaders specified by webpack configuration rules, with optional .js extension suffix. For example a.scss can be compiled into file a.scss.js, with its content
    document.head.insertAdjacentHTML("beforeEnd", `<style>Generated CSS text</style>`);
  3. Commonjs require is compiled into synced XHR
// Pseudo code
function require(id) {
  const moduleId = getAbsolutePathSomehow(id);

  if (installedModules[moduleId]) {
    return resolvedModules[moduleId].exports;
  }

  const req = new XMLHttpRequest();
  req.open("GET", moduleId, false);
  req.send();
  const module = require.installedModules[moduleId] = {
    id: moduleId,
    loaded: false,
    exports: {},
  };
  new Function('module', 'exports', 'use strict;\n' + req.responseText)
    .call(module.exports, module, module.exports);
  module.loaded = true;
  return module.exports;
}
require.installedModules = {};

globalThis.require = require;

Another option is compiling commonjs module into ES6 default-export module.

Related issue: webpack/webpack#8010 (comment)

@CarterLi - I agree, being able to use Webpack for outputting unflattened ES6 files would be great - but that's 100% to do with Webpack, and not this plugin.