1唉窃、安裝
打開node,敲入命令行
①全局安裝
$ npm install webpack -g
②安裝在項目中纹笼,將依賴寫入package.json
$ npm init
$ npm install webpack --save-dev
2纹份、編譯
在項目文件下
①新建一個文件entry.js并輸入內(nèi)容:
document.write("hello world!");
②新建一個index.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>
③node里敲命令,編譯文件
$ webpack ./entry.js bundel.js
3、組件
entry.js是入口文件蔓涧,一般還有各個組件模塊件已,從而引用實現(xiàn)復(fù)用。
①新建一個component.js文件元暴,輸入
module.exports = "It works from component.js";
②修改入口文件entry.js
//document.write("hello world!");
document.write(require("./component.js"));
③node敲命令重新編譯篷扩,然后去瀏覽器里刷新查看
$ webpack ./entry.js bundel.js
4、css-loader和style-loader以及wepack.config.js
css-loader用來處理CSS文件茉盏;style-loader將樣式應(yīng)用在CSS文件上
①node里敲命令安裝這兩個模板
$ npm install css-loader style-loader --save-dev
②新建一個style.css文件
body{
background:red;
}
③更新修改entry.js
require("./style.css");
document.write(require("./content.js"));
④在項目文件下新建一個webpack.config.js文件并輸入
module.exports = {
entry: "./entry.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /.css$/, loader: "style-loader!css-loader" }
//注意:這里的style和css后面都要加"-loader"后綴鉴未,官網(wǎng)上教程沒有更新,詳情:https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
]
}
};
⑤node里敲命令編譯
這個時候只需要敲webpack就可以了鸠姨,因為Webpack 在執(zhí)行的時候铜秆,除了在命令行傳入?yún)?shù),還可以通過指定的配置文件來執(zhí)行讶迁。默認情況下连茧,會搜索當前目錄的webpack.config.js
$ webpack