首頁 > web前端 > js教程 > 主體

Webpack載入模組有哪些方法

php中世界最好的语言
發布: 2018-05-25 10:55:16
原創
1130 人瀏覽過

這次帶給大家Webpack載入模組有哪些方法,Webpack載入模組的注意事項有哪些,下面就是實戰案例,一起來看一下。

兩個簡單的原始檔案

為了方便分析webpack 載入模組的原理,我們準備了兩個檔案:

hello.js

const hello = {
 say: arg => {
  console.info('hello ' + arg || 'world');
 }
};
export default hello;
登入後複製

index.js

import Hello from './hello';
Hello.say('man');
登入後複製

index.js 作為入口檔,引用了hello.js 模組。

Webpack 打包

在命令列執行webpack index.js bundle.js 對入口檔進行打包,產生bundle.js ,大體結構為(為了方便閱讀,我刪除了部分多餘的程式碼):

#可以看到,最終產生的檔案以(function (modules) {})([模組1, 模組2]) 的方式啟動,我們定義的模組被包裝成一個個匿名函數,然後以數組的形式傳遞個一個匿名函數function (modules) {},在這個匿名函數中定義了一個webpack_require() 函數,用來載入模組,最後,透過return webpack_require(webpack_require.s = 0); 來載入第一個模組index.js

#webpack_require() 函數

該函數接收一個moduleId 作為參數,這個參數就是各個模組在陣列中的索引,

function webpack_require(moduleId) {
  /******/
  /******/ // Check if module is in cache
  /******/
  if (installedModules[moduleId]) {
   /******/
   return installedModules[moduleId].exports;
   /******/
  }
  /******/ // Create a new module (and put it into the cache)
  /******/
  var module = installedModules[moduleId] = {
   /******/
   i: moduleId,
   /******/
   l: false,
   /******/
   exports: {}
   /******/
  };
  /******/
  /******/ // Execute the module function
  /******/
  modules[moduleId].call(module.exports, module, module.exports, webpack_require);
  /******/
  /******/ // Flag the module as loaded
  /******/
  module.l = true;
  /******/
  /******/ // Return the exports of the module
  /******/
  return module.exports;
  /******/
 }
登入後複製

其中installedModules 是用來緩存執行過的模組。透過 modules[moduleId].call() 來執行模組,最後返回模組的 exports。

模組接受的參數

以hello.js 模組為例

 (function (module, webpack_exports, webpack_require) {
  "use strict";
  const hello = {
   say: arg => {
    console.info('hello ' + arg || 'world');
   }
  };
  /* harmony default export */
  webpack_exports["a"] = (hello);
  /***/
 })
登入後複製

webpack 會傳遞

## module, webpack_exports, webpack_require

三個參數,前兩個是用來導出模組內的變量,第三個參數為前面介紹的

webpack_require()

的引用,用來導入其它

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:

node.js部署啟動後台運行forever步奏詳解

######正規表示式中的\ B和\b使用步驟詳解##########

以上是Webpack載入模組有哪些方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!