With the rapid development of front-end frameworks, modularity has become commonplace but people don’t know the difference between script and require (import). How to import depends on how to export before, when refactoring a captcha old project, do not know how to export the project to be able to import via script and then use internal methods?

The scenario is simplified as follows:

  • The plug-in code
import {util} from 'util'
import styles from 'css'
export function initA(){
	console.log('it is init')... }Copy the code
  • Bundled as bundle.js via the common Webpack and introduced in HTML
<script src="bundle.js"InitA undefined initA() </script>Copy the code

The analysis reason

InitA = ‘window’; initA = ‘window’; initA = ‘window’; initA = ‘window’;

(function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.initA = initA;
function initA() {
    console.log('it is initA'); }})Copy the code

How can you export variables and mount them on global objects

Var _jQuery = window.jQuery, _$= window.$; var jQuery = window.jQuery = window.$ =function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context );
    };
Copy the code

After much searching, the output module specification can be configured with the output.libraryTarget parameter in the Webpack configuration.

Webpack libraryTarget Parameter Description

Library will cancel the “var” configuration if output.library is not specified

  • LibraryTarget: “var” (default) output.library exports the value as a variable declaration (which is available in global scope after execution when using script tags).
  • LibraryTarget: “window” When the Library is loaded, the return value from the entry point is assigned to the Window object.
window["MyLibrary"] = _entry_return_; / / the user will have you call your library: window. MyLibrary. DoSomething ();Copy the code
  • libraryTarget: “assign”
  • libraryTarget: “this”
  • libraryTarget: “global”
  • LibraryTarget: “CommonJS” When the Library is loaded, the return value from the entry start is assigned to the Exports object. This name also means that the module is used in the CommonJS environment
exports["MyLibrary"] = _entry_return_; // The user will call your library: require("MyLibrary").doSomething();
Copy the code
  • libraryTarget: “commonjs2”
  • libraryTarget: “amd”
  • LibraryTarget: “UMD” this is a way of making your library run under all module definitions (and exporting not modules at all). It will run in CommonJS, AMD environment, or export the module to the final output of the variable under Global:
(function webpackUniversalModuleDefinition(root, factory) {
  if(typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if(typeof define === 'function' && define.amd)
    define([], factory);
  else if(typeof exports === 'object')
    exports["MyLibrary"] = factory();
  else
    root["MyLibrary"] = factory();
})(this, function() {// This module will return what your entry chunk returned});Copy the code
  • libraryTarget: “jsonp”

Compare var, Window,global, umD

The difference between the browser environment and node environment results in the difference between window (client browser) and Global (Node server). Var in my understanding is the same as window when script is imported. Whether it can be imported through import or not needs to be explained. Umd supports customization in all cases. In general, setting up library means importing library files globally in the current environment.

A simple use of externals

How is externals used? How is it different from module exports? Let’s start with the definition: the externals configuration option provides a method to “exclude dependencies from the output bundle.” This means that webpack does not pack the library into the bundle, so the developer needs to introduce it in the HTML via the script tag. For example, importing jQuery from CDN instead of packaging it:

index.html

<script src="https://code.jquery.com/jquery-3.1.0.js"
  integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
  crossorigin="anonymous"></script>
Copy the code

webpack.config.js

externals: {
  jquery: 'jQuery'
}
Copy the code

If you’re interested, you might wonder, why do I need to set this configuration when I’ve already imported it from the script tag? In order not to change the original dependency module! The following

import $ from 'jquery';

$('.my-element').animate(...) ;Copy the code

Bundles with external dependencies can be used in various module contexts, such as CommonJS, AMD, global variables, and ES2015 modules. The pattern in question is the same as that of libraryTarget. An external library may take any of the following forms:

  • Root – External library can be used as a global variable. Users can do this by importing it in script tags. This is the default setting for externals.
  • Commonjs – User (consumer) applications may use the CommonJS module system, so external libraries should use the CommonJS module system, and it should be a CommonJS module.
  • Commonjs2 – similar to the above lines but exported as module.exports.default.
  • Amd – Similar to the above lines, but using the AMD module system.

Before only watch nuggets, never send, welcome to follow my blog ah.