webpack基本使用

1.先确认是否安装了nodejs:
npm -v
2.安装webpack:
npm init,创建package.js
npm install webpack --save-dev
或者(npm i webpack -g)
3.导航到项目文件夹
js打包:
./node_modules/.bin/webpack hello.js hello.bundle.js
引入css:
./node_modules/.bin/webpack hello.js hello.bundle.js --module-bind "css=style-loader!css-loader"
******window环境下可能要加粗体字部分
--config configfilename.js
--watch
--progress
--display-modules
--display-reasons
-----------------------------------基本配置-------------------
上面是CLI(Command Line Interface)模式,手写命令行执行wp,但也可以更方便地使用wp,通过设置webpack.config.js,以后直接在index目录下执行“webpack”就可以执行wp各项功能了
1.添加配置文件:
创建webpack.config.js:
module.exports={
      entry:'xxx',
      output:{
      path:'',
      filename:''
      }
}

命令行切换到index页面目录,直接webpack就可以执行(没有修改package.js)
2.观察者模式:
Webpack为我们提供了观察者模式,启用后,任何的webpack.config.js中的变化将接受观察,自动生成最终的js文件。
命令行来到网站目录下
启用观察者模式
webpack --watch
→ 在webpack.config.js中添加watch字段,并设置成true
module.exports = {
entry: "./app.js",
output: {
filename: "bundle.js"
},
watch: true
}
这样,每次修改保存webpack.config.js中引用文件,bundle.js的文件会自动更新。


通过修改package.json
strict:{
...
'webpack':'--config xxx --progress --display-reasons --display-modules --color'
}
之后:

  npm run webpack

entry的三种方式:
字符串路径
数组路径(互不依赖)
对象形式( 这是针对多页面应用的):
{
page1:'',
page2:[]
}此时output的filename要改'[name]-[hash]-[chuckhas].js',否则生成文件名相同会把文件覆盖。
问:生成多个文件的时候,难道需要一个个手动修改页面中引用的文件路径(或文件名)吗?
答:不用,可以用html-webpack-plugin插件。
npm  i html-webpack-plugin --save-dev

config.js文件中引入:var htmlWebpackPlugin=require("html-webpack-plugin");
调用插件时,config文件中调用对象plugins
plugins:[
new htmlWebpackPlugin ()
]
插件实例中传入参数对象:
{
template:“index.html” //生成html的母模板

}
plugins:[
      new htmlWebpackPlugin({
      template:'temp_path',    //母模版
      filename:'index-[hash].html',  文件名
      inject:'head'  ...['body'],    //引用文件插入位置  可以设置为false
      title:'xxx',                //生成的页面的title
      date:new Date()
      })
      ]
默认生成在output目录中

module.exports默认有个context属性,上下文为根目录
****************************************插件语法*****************************
在index.html里面可以用模板语法:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值