首页 > 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学习者快速成长!