element ui框架(webpack打包器)

語言: CN / TW / HK

【 聲明:版權所有,歡迎轉載,請勿用於商業用途。 聯繫信箱:feixiaoxing @163.com】

在前端開發中一般會用到webpack打包器。雖然使用npm run build會自動調用webpack幫助我們打包,不過還是建議大家可以手動編寫代碼,看一下打包的過程究竟是怎麼樣的。

1、安裝webpack、webpack-cli

npm install webpack webpack-cli -g

2、創建一個webpack目錄

因為這裏只是測試一下webpack的用法,本身用不到vue。所以這裏就不再需要用vue init創建工程代碼了。

3、創建hello.js文件

在webpack目錄下面再創建一個modules目錄,hello.js文件就是放在這個modules目錄下面。其中hello.js文件的內容如下所示,

exports.sayhi = function(){
	document.write("<div>Hello world</div>")
}

4、繼續創建main.js文件

在modules目錄下面繼續創建main.js文件,內容如下所示,

var hello=require("./hello")
hello.sayhi()

5、接着準備webpack.config.js文件

有了hello.js和main.js之外,下面就可以準備webpack.config.js文件了。這個文件是為webpack命令準備的,文件本身和modules目錄在同一層,內容如下,

module.exports = {
	
	entry: "./modules/main.js",
	output: {
		filename:"./js/bundle.js"
	},
	watch:false
	
}

6、輸入webpack命令

輸入命令後,不出意外,就可以看到一個dist目錄。dist/js目錄下面有一個bundle.js文件,這就是壓縮好的文件。內容本身已經不好辨認了。

(()=>{var r={645:(r,o)=>{o.sayhi=function(){document.write("<div>Hello world</div>")}}},o={};(function t(e){var i=o[e];if(void 0!==i)return i.exports;var n=o[e]={exports:{}};return r[e](n,n.exports,t),n.exports})(645).sayhi()})();

7、準備index.html文件

為了驗證壓縮後的bundle.js是否可以真正運行起來,可以準備一個index.html文件。在html文件中引用這個bundle.js文件,內容如下,

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title> webpack測試 </title>
	</head>
	<body>
		<script src="./dist/js/bundle.js"></script>
	</body>

</html>

8、用firefox或者chrome打開index.html,