webpack 是一個(gè)可以將一些js、css、圖片、json、自定義的等類(lèi)型的文件通過(guò)webpack打包成一個(gè)或多個(gè)bundle的工具。
// hello.js
function sayHello(str) {
alert(str);
}
上述文件可以通過(guò)命令webpack hello.js hello.bundle.js進(jìn)行打包,并在html文件中引入打包過(guò)后的文件。
<!doctype html>
<html>
<head>
<meta charset="utf-8"></meta>
<title>webpack test</title>
</head>
<body>
<script type="text/javascript" src="./hello.bundle.js"></script>
</body>
</html>
可以在hello.js文件中引入其他的文件,比如js文件、css文件。
// welcome.js
export object = {};
/* style.css */
html, body {
margin: 0;
padding: 0;
}
body {
background-color: red;
}
// hello.js
require("./welcome.js");
require("./style.css");
function sayHello(str) {
alert(str);
}
hello.js文件中的require命令是CommonJS的語(yǔ)法。使用命令webpack hello.js hello.bundle.js進(jìn)行打包時(shí)會(huì)報(bào)錯(cuò),因?yàn)?code>style.css文件需要安裝適當(dāng)?shù)膌oader,運(yùn)行命令npm install css-loader style-loader --save-dev安裝style-loader和css-loader。修改hello.js文件
// hello.js
require("./welcome.js");
require("style-loader!css-loader!./style.css");
function sayHello(str) {
alert(str);
}
使用css-loader來(lái)處理以.css結(jié)尾的css文件,再將處理過(guò)后的代碼用style-loader新建style標(biāo)簽插入到html文檔中。