WebPack(Ⅱ)

webpack是模块化打包工具,那么webpack到底是怎么样进行模块化的呢?我们在引入js文件的时候是通过许多的<script>标签进行引入的,那么我们可不可以将这么多js文件合并成一个js文件,再进行引入呢?这样可以减少香服务器请求次数,加载速度可以加快。下来我们开始!

一、在app-test下面建立一个js文件夹,里面有两个js文件,一个是test.js文件,一个是index.js文件。它们的内容如下:

//test.js
console.log("我是test.js");
//index.js
console.log("我是index.js");

二、接下来在我们将两个js合并为一个js文件之前,我们先来了解一下webpack.config.js文件里面entry的值的类型:

entry:."/js/index.js"			                //string
entry:["./js/test.js","./js/index.js"]			//array        把多个文件打包成一个文件,哪个先执行,就把哪个写在前面
entry:{
	a:"./js/test.js",
	b:"./js/index.js"
}							//object

三、我们要把两个js文件合并成一个js文件,我们将test.js和index.js打包到build下面的bundle.js,那么我们选择第二种:


四、打包后的文件bundle.js的文件内容是:

!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t){console.log("我是index.js")},function(e,t){console.log("我是test.js")},function(e,t,n){n(1),e.exports=n(0)}]);

打包好以后,我们只需要引入bundle.js一个文件,即可执行两个js文件,用浏览器打开index.html在控制台就可以看见输出结果。

五、下面我们在app-test下面出啊构建一个文件夹叫做public,里面建立了test.html文件和list.html文件,在js文件夹下面再建立一个list.js文件,内容如下:

//list.js
console.log("我是list.js");

目前文件app-test下面的文件情况如下:


六、一般情况下,我们不同的html文件引入不同的js文件,那么我们就选择entry的类型为object。在进行这之前,我们先了解一下output的值的类型:

output:{
	path:path.resolve(__dirname,'build'),
	filename:"bundle.js"		//string用于单个入口点
	filename:"[name].js"		//用于多个入口点
	filename:"[chunkhash].js"	//用于长效缓存
}

七、我们此时采取的出口文件就是filename:“[name].js",name会遍历入口的所有键值,将键值作为新打包文件的文件名(如下示例中,键值就是index,test,list)。webpack.config.js文件内容如下,我们在打包之前将build文件下的内容清空。


八、现在我们用npm run build命令进行打包,如下图是打包结果的信息显示:


我们去build文件夹下面会发现有三个打包好的js文件,分别是list.js,test.js,index.js。然后我们就可以将打包的三个js文件引入不同的html文件。

微总结:本次主要认识了webpack.config.js文件夹下的entry和output的值的类型。

猜你喜欢

转载自blog.csdn.net/zhanghuali0210/article/details/80940642