webpack的基本使用(一)

来源:互联网 发布:海口网络推广公司 编辑:程序博客网 时间:2024/06/06 04:22

-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:列出打包模块的原因