webpack中imports-loader,exports-loader,expose-loader的区别
2017-01-20 15:56
453 查看
Webpack有几个和模块化相关的loader,
例子完整的代码可以点这里
我们的配置文件中,是把
注意,我们并没有引入
但是如果我们稍微修改一下
当然,这个能运行之前,我们要
例子的完整代码在 这里
然后我们在
例子中的注释是说
我这里还有一个稍稍复杂点的从一个umd模块的文件里导出到全局变量的例子,有兴趣的同学点击这里。
imports-loader,
exports-loader,
expose-loader,比较容易混淆。今天,我们来理一理。
imports-loaders
文档介绍的是:用于向一个模块的作用域内注入变量(Can be used to inject variables into the scope of a module.),官方的文档总是言简意赅但是不太好懂。我们来举个例子。例子完整的代码可以点这里
jqGreen.js文件里仅一行代码
//没有模块化 $('#box').css('color','green');
index.js文件也只有一行代码
require('./jqGreen');
我们的配置文件中,是把
index.js作为入口文件的。
{ entry:{ index:'./src/js/index.js' } }
注意,我们并没有引入
jquery。所以运行的结果是
$ is not defined。
但是如果我们稍微修改一下
jqGreen的引入方式,就能很轻松的解决这个问题。
index.js文件
require('imports?$=jquery!./jqGreen');
当然,这个能运行之前,我们要
npm install imports-loader一下。上面代码,把变量
$注入进模块
jqGreen.js。同时,我们指定了变量
$=jquery。等于是在
jqGreen.js文件的最顶上,加上了
var $=require('jquery')。这样,程序就不会报
$ is not defined的错误了。
exports-loader
exports有导出的意思,这让我们猜测它有从模块中导出变量的功能。实际情况大致如此。我们来看个小例子。
例子的完整代码在 这里
Hello.js文件中仅有一个方法,直接绑定在全局变量
window上面。
window.Hello = function(){ console.log('say hello.'); }
然后我们在
index.js文件里去引用这个
Hello.js:
var hello = require('./Hello.js');。这样引用的结果是变量
hello是
undefined。因为我们在
Hello.js文件里没有写
module.exports=window.Hello,所以
index.js里我们
require的结果就是
undefined。这个时候,
exports-loader就派上用场了。我们只用把
index.js的代码稍微改动一下:
var hello = require('exports?window.Hello!./Hello.js');,这个时候,代码就能正确的运行了。变量
hello就是我们定义的
window.hello啦。
var hello = require('exports?window.Hello!./Hello.js');这行代码,等于在
Hello.js里加上一句
module.exports=window.Hello,所以我们才能正确的导入。
expose-loader
把一个模块导出并付给一个全局变量。文档里给了一个例子:require("expose?libraryName!./file.js"); // Exposes the exports for file.js to the global context on property "libraryName". // In web browsers, window.libraryName is then available.
例子中的注释是说
把file.js中exports出来的变量付给全局变量"libraryName"。假如
file.js中有代码
module.exports=1,那么
require("expose?libraryName!./file.js")后
window.libraryName的值就为1(我们这里只讨论浏览器环境)。
我这里还有一个稍稍复杂点的从一个umd模块的文件里导出到全局变量的例子,有兴趣的同学点击这里。
相关文章推荐
- webpack中imports-loader,exports-loader,expose-loader的区别
- Webpack载入loader,imports-loader,exports-loader,expose-loader
- webpack构建VUE项目使用jquery及其插件 expose-loader
- 【webpack】expose-loader 插件使用
- webpack:使用expose-loader 解决第三方库的插件依赖问题
- Webpack 中 file-loader 和 url-loader 的区别
- Vue + Webpack + Vue-loader 1
- Webpack中hash与chunkhash的区别,以及js与css的hash指纹解耦方案
- Gulp和webpack的区别,是一种工具吗?
- webpack 的 loader 和 plugin
- Vue + Webpack + Vue-loader 系列教程
- webpack入门和实战(二):全面理解和运用loader和plugins
- webpack less-loader出现异常
- webpack loader
- webpack loader
- Webpack中hash与chunkhash的区别,以及js与css的hash指纹解耦方案
- extract-text-webpack-plugin" loader is used without the corresponding plugin How to deal
- [Webpack 2] Expose modules to dependencies with Webpack
- 详情介绍webpack-dev-server,iframe与inline的区别
- webpack与gulp的区别及实例搭建