首页投稿(暂停使用,暂停投稿)

CommonJs require.ensure use in w

2017-06-22  本文已影响0人  a_pioneer

I know require, but what is require.ensure. Let explore how to use it.

1. source file

Now, I have 5 files, a.js, b.js, c.js, d.js and example.js

// a.js
console.log('a module here');
// b.js
console.log('b module here');
// c.js
console.log('c module here');
// d.js
console.log('d module here');
// example.js
var a = require('./a');
var b = require('./b');

require.ensure(['./c'], function(require) {
  require('./b');
  var d = require('./d');
});

2. complie

let complie example.js by webpack ./node_modules/.bin/webpack example.js bundle.js. We get two files as result, bundle.js and 0.bundle.js.

// bundle.js

/******/ (function(modules) { // webpackBootstrap
/******/  // install a JSONP callback for chunk loading
/******/  var parentJsonpFunction = window["webpackJsonp"];
/******/  window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {
/******/    // add "moreModules" to the modules object,
/******/    // then flag all "chunkIds" as loaded and fire callback
/******/    var moduleId, chunkId, i = 0, resolves = [], result;
/******/    for(;i < chunkIds.length; i++) {
/******/      chunkId = chunkIds[i];
/******/      if(installedChunks[chunkId]) {
/******/        resolves.push(installedChunks[chunkId][0]);
/******/      }   
/******/      installedChunks[chunkId] = 0;
/******/    }   
/******/    for(moduleId in moreModules) {
/******/      if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/        modules[moduleId] = moreModules[moduleId];
/******/      }   
/******/    }   
/******/    if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);
/******/    while(resolves.length) {
/******/      resolves.shift()();
/******/    }   
/******/
/******/  };  
/******/
/******/  // The module cache
/******/  var installedModules = {}; 
/******/
/******/  // objects to store loaded and loading chunks
/******/  var installedChunks = { 
/******/    1: 0
/******/  };  
/******/
/******/  // The require function
/******/  function __webpack_require__(moduleId) {
/******/
/******/    // Check if module is in cache
/******/    if(installedModules[moduleId]) {
/******/      return installedModules[moduleId].exports;
/******/    } 
// 0.bundle.js

webpackJsonp([0],[
/* 0 */,
/* 1 */
/***/ (function(module, exports) {

console.log('c module here');


/***/ }), 
/* 2 */,
/* 3 */,
/* 4 */
/***/ (function(module, exports) {

console.log('d module here');


/***/ })
]);

3. Use bundle.js in html

// index.html
<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <script src="bundle.js"></script>
  </body>
</html>

open index.html in browser

image.png
// example.js
var a = require('./a');
var b = require('./b');

require.ensure(['./c'], function(require) {
  require('./b');
  var d = require('./d');
  require('./c');
});
image.png

4. summary

上一篇下一篇

猜你喜欢

热点阅读