How to build and use your own 3rd party JS library with webpack?
为情所困
为情所困 2017-05-19 10:47:18
0
3
521

I’m curious about things like jQuery, React These packaged libraries can be used globally after loading $, jQuery and React comes to visit and wants to know how the library you built can be used globally like React.

I found that after webpack packaging, the related objects defined could not be found globally at all.

为情所困
为情所困

reply all(3)
曾经蜡笔没有小新

Package it into a library, please read https://webpack.js.org/guides...

给我你的怀抱

After webpack is packaged, it is all closures. How can it be accessed globally?

In order to have global access, the relevant configuration of new webpack.ProvidePlugin must be added to webpack

For example

new webpack.ProvidePlugin({$: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery'})
为情所困

Generally, just register your main object (or class) directly to the global object. For example, you can imitate the jQuery registration method (removing the section that determines document):

(function(global, factory) {
    "use strict";
    // 兼容模块化框架(主要是 AMD 框架)
    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = factory(global);
    } else {
        factory(global);
    }
})(typeof window !== "undefined" ? window : this, function(global) {
    // 这里是你的库代码
    global = MyLibEntry;
});

If you adopt a modular writing method, you can write the above code on the entry module.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template