webpack的基本使用(一)

-webpack的安裝
本地項目下安裝:npm install webpack –save-dev
-示例1
hello.js

function hello(str){
alert(str)
}

打包:webpack hello.js(要打包的文件的名稱) hello.bundle.js(打包後文件的名稱)
結果:
這裏寫圖片描述
-asset:是指打包生成的文件
-size:文件大小
-chunks:打包的分塊
-chunk names:塊名稱
-示例2
新建world.js

function world(){
 return{
 }
}

在hello.js中引用world.js

require('./world.js')
function hello(str){
alert(str)
}

再次運行上面的命令
結果:
這裏寫圖片描述
-webpack對css文件的處理
新建style.css

html,body{
    margin:0;
    padding: 0;
}

在hello.js文件中引入style.css

require('./world.js')
require('css-loader!./style.css')//css-loader!的意思是:引用style.css文件前先用css-loader處理
function hello(str){
    alert(str)
}

在命令行引用相應的loader
-npm webpack css-loader style-loader –save-dev
再次運行以上命令打包。
注意:當出現You may need an appropriate loader to handle this file type.錯誤提示時,說明沒有引用相應的loader。
-在index.html頁面中進入js文件
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webpack test</title>
</head>
<body>
  <script type="text/javascript" src='hello.bundle.js'></script>  
</body>
</html>

修改hello.js文件

require('./world.js')
require('css-loader!./style.css')
function hello(str){
    alert(str)
}
hello('hello world')

再次打包,並在瀏覽器打開index.html運行成功。
-**當修改css文件後,若想生效需要引入style-loader

require('style-loader!css-loader!./style.css')

css-loader:使得webpack可以處理css文件
style-loader:在html頁面新建一個style標籤,將css-loader處理完的文件插入
當引入的css文件過多時的處理
當引入的css文件過多時,不必爲每個引入的文件加入css-loader.
在命令行中可以使用module-bind ‘參數’
例如:
webpack hello.js hello.boundle.js --module-bind 'css=style-loader!css-loader'–watch
–watch:當文件改變時自動打包
錯誤:
webpack使用css-loader提示Module build failed: Unknown word (5:1)
解決方法:在bash下出現該問題,在cmd中打包成功
這裏寫圖片描述
-其它參數

  • –progress:可以查看打包過程
  • –display-modules:列出引用的所有模塊
  • –display-reasons:列出打包模塊的原因
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章