Webpack — 概念

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-loadercss-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文檔中。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容