你的位置: 首页 开发,项目

webpack expose-loader exports-loader区别

2016-03-30 12:23:56

按字面意思理解是很困难的,暴露导出,实际上区别很大,做下实验:

三个文件,require.html entry.js content.js

<!DOCTYPEhtml>

<htmllang="en">

<head>

<metacharset="UTF-8">

<title>testrequire</title>

<scriptsrc="bundle.js"></script>

</head>

<body>

 

</body>

</html>

entry.js:

document.write(require("./content.js"));

content.js:

module.exports="i'mthedatathatyouwanted!";

执行webpack entry.js bundle.js生成bundle.js

渲染效果如下:

Machine generated alternative text: C localhost:63342/testWebpack/require.html  i'm the data that you wanted!

很简单的一个基本环境,就引入entry,write content.js的内容。

 

先实验expose-loader

npm install expose-loader

 

修改content.js 引入一个内部变量 insideData

varinsideData="I'mhiding";

module.exports="I'mthedatathatyouwanted!";

 

修改entry.js,expose导出insideData

document.write(require("expose?insideData!./content.js"));

console.log(insideData);

console.log(window.insideData);

 

效果如下

Machine generated alternative text: I'm the data that you wanted!  1 Elements  top  I'm the data that  I'm the data that  Console Sources  you wanted!  you wanted!  Network Timeline  Preserve log

发生了什么? console出来的并不是我们的insideData,而是exports出来的变量。所以expose并不是暴露包内部的变量,而是把包的exports变量暴露到全局空间。参数是可以随便自定义的。

 

再实验exports-loader

安装exports-loader, npm install exports-loader

entry.js,跟之前差不多,不过把expose换成exports:

document.write(require("exports?insideData!./content.js"));

console.log(insideData);

console.log(window.insideData);

content.js不变,效果如下:

Machine generated alternative text: I'm hiding  v top  Elements Console Sources Network Timeline Profiles >>  [E bundle.js x  O Serving from the file system? Add your files into the work..  01  x  . more never show x  v O localhost:  v testWeb  requir  bundl  > O (no domai  49  50  51  52  53  document . write( webpack_require_(l) ) ;  console. log(insideData); O  console. )  'Uncaught ReferenceError: insideData is not defined  Line 51, Column 14

require返回的东西换成了insideData,而不是原先定义的内容,所以exports插件理解也很简单,就是把导出的变量换掉,不带修改作用域功能。

 

总结

expose插件将module的exports变量暴露到全局空间。

exports插件将module的exports变量换掉


©翟四岚 1989-2089