Include unpacked JavaScript code as a module

How do I get a JavaScript library that is not packaged as a UMD-compatible module (AMD, CommonJS) with webpack?

I do not want the library to go through the bootloader. I just want it to be included in the tag <script>whenever it is required, and for webpack to manage this dependency.

I don’t want to just put it in the script tag in mine index.html, because I want to use webpack code splitting and only enable it if necessary.

I read about the "external", I'm not sure if this has anything to do with it. The documents are not clear enough.

Thanks:)


Updated Question

This question also concerns front-end libraries, which need to be included only with the help of a tag <script>.

+4
source share
1 answer

You can add amd support to your library and then load it using webpack. Some links that may help you are as follows:

What is basically being done is that at the top of your library you can check if this is a commonjs environment or an AMD environment. Accordingly, you can export your library.

One example would be this (taken from 1st link )

(function (root, factory) {
  if(typeof define === "function" && define.amd) {
    // Now we're wrapping the factory and assigning the return
    // value to the root (window) and returning it as well to
    // the AMD loader.
    define(["postal"], function(postal){
      return (root.myModule = factory(postal));
    });
  } else if(typeof module === "object" && module.exports) {
    // I've not encountered a need for this yet, since I haven't
    // run into a scenario where plain modules depend on CommonJS
    // *and* I happen to be loading in a CJS browser environment
    // but I'm including it for the sake of being thorough
    module.exports = (root.myModule = factory(require("postal")));
  } else {
    root.myModule = factory(root.postal);
  }
}(this, function(postal) {
  // module code here....
  return myModule;
}));
0
source

Source: https://habr.com/ru/post/1622194/


All Articles