学习webpack(二)

1.在webpack.config.js中写入以下代码

var path = require('path');      // 导入路径包 
module.exports={ 
    entry:'./src/script/main.js',//入口文件 
    output:{ 
        path:path.join(__dirname, 'dist'),// 指定打包之后的文件夹 
        filename:'bundle.js' // 指定打包为一个文件 bundle.js 
    }
}

运行:webpack 即可

2. entry可以设置两个参数['./src/script/main.js','./src/script/a.js']

entry也支持对象的写法

var path = require('path');      // 导入路径包 
module.exports={ 
    entry:{
    	main:'./src/script/main.js',//入口文件 
    	a:'./src/script/a.js'
    },
    output:{ 
        path:path.join(__dirname, 'dist'),// 指定打包之后的文件夹 
        filename:'bundle.js' // 指定打包为一个文件 bundle.js 
    }
}

3.这样有个缺点,打包后就只有一个文件bundle.js ; 下面是改进的方案

var path = require('path');      // 导入路径包 
module.exports={ 
    entry:{
    	main:'./src/script/main.js',//入口文件 
    	a:'./src/script/a.js'
    },
    output:{ 
        path:path.join(__dirname, 'dist'),// 指定打包之后的文件夹 
        filename:'[name]-[hash].js ' // 指定打包为一个文件 bundle.js 
    }
}


4.由于打包后的文件个数不确定,所以html中引入的文件不定固定为bundle.js

解决方案:引入插件 html-webpack-plugin

5.入口多个js文件,打包后html中分类显示([name]-[hash])



6.可以在html中通过<%=%>语法获得htmlWebpackPlugin插件的连个参数(files,options),循环遍历可以显示


打包后就会显示


这样就可以在html网页中分类显示js的位置,是在body中,还是在head中



7.将打包的地址替换为上线的地址


打包后:


在plugins中增加minify属性,就是压缩html代码

删除注释和空格

plugins:[
    new webpack.optimize.UglifyJsPlugin(), // 用于压缩js文件
    new htmlWebpackPlugin({ // 打包的模板套用根目录的index.html 
      template: 'index.html',
      title:'webpack is good',
      date: new Date(),
      inject:false,  // 打包后的js文件放在html的header标签中
      minify:{ // 对当前生成的html文件进行压缩
        removeComments: true,  // 删除注释
        collapseWhitespace: true // 删除空格
      }
    })     
  ]  

打包后:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值