webpack深入与实战

安装

mrdir my-project                //创建文件
cd my-project                   //进入文件
npm init                        //初始化配置文件
npm install webpack --save-dev  //安装webpack

基本打包命令

webpack hello.js hello.bundle.js
其中hello.js为自己编写的文件,hello.bundle.js为打包后文件

当打包css文件时,可以在文件内通过引入loader进行打包

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

也可以在命令行中直接通过命令打包

webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader'

添加 –watch 命令可以动态观察文件变化并进行打包
–progress 命令可以显示百分比读条
–display-modules 可以列举出模块
–display-reasons 可以列举出打包模块原因

webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader' --progress --display-modules --display-reasons --watch

配置文件

配置文件是默认的文件名(webpack.config.js)

  1. 在文件的根目录下创建webpack.config.js文件
  2. 配置参数

    var path = require(‘path’);
    module.exports = {

    entry:'./src/script/main.js',//打包的入口
    output:{
        path: path.resolve(__dirname, 'dist/js'),//打包后的存放路径     (绝对路径)
        filename:'bundle.js'//打包后的文件名
    }
    

    }

  1. 在命令行 中运行:webpack

配置文件不是默认的文件名

  1. 比如配置文件的文件名为webpack.dev.config.js
  2. 在命令行中运行时:webpack –config webpack.dev.config.js

设置webpack参数

  1. 在npm脚本文件package.json文件中设置
  2. 在scripts中添加:”webpack”:”webpack –config webpack.config.js –progress –display-modules –colors –display-reasons”

webpack的三种用法

1.直接命令行使用。
2.node.js API的使用方式。
3.webpack —config webpack.config.js

entry

entry用于定义入口文件

1.三种输入方式

(1)string,输入字符串
entry:{
main:’./src/script/main.js’
},

(2)array, 数组。适用情况:两个平行的,不相依赖的文件打包在一起。
entry:{
main:[‘./src/script/main.js’,’./src/script/a.js’]
},

(3)object, 适用情况:多页面应用程序。这里要和output里的[name]占位符配合使用,威力才能最大。如果你要打包成多个js文件,那么entry对象里的key叫做chunk就是文件名,里面的值就是需要打包的文件里面包含的文件。
entry:{
main:’./src/script/main.js’,
a:’./src/script/a.js’
},

output

1.占位符有3种:[name]、[hash]、[chunkhash]

2.output的filename
(1)hash: 这次打包的hash
每次终端运行webpack命令,都会生成一段信息,这段信息的第一行就有一个hash
(2)chunkhash:每一个chunk自己的hash

3.output的path,//这里配置的是输出的文件地址

自动生成html页面

html中引入script,如果是hash或者chunkhash生成的js,则src每次都要修改,避免修改的方法就是用webpack的插件:

1.安装webpack插件:
终端项目目录输入:npm install html-webpack-plugin –save-dev

2.配置文件中建立对插件的引用
webpack.config.js中
(1)引用插件

var htmlWebpackPlugin=require('htmll-webpack-plugin');

(2)以index.html为模板

设置plugins:[
    new htmlWebpackPlugin()// 初始化插件
]

这里的代码只会让webpack自动生成一个index.html,里面自动把js代码插入到index.html当中。//注意,这里说的是webpack生成的index.html,不是你自定义的index.html。
要想让生成的index.html是自定义的,那么就要设置

plugins:[
    new htmlWebpackPlugin({
        template: ‘index.html’,//   这里的index.html就是根目录下的index.html文件,是你自己写的文件。
        filename: ‘index-[hash].html’,//这里指定的是生成的文件的名字
         inject: 'body’,// 这里可以指定js文件是放在head还是body标签里面具体还可  以放哪,请看文档说明。https://github.com/jantimon/   html-webpack-plugin#configuration
    })// 初始化插件
]

(4)webpack使用插件的地址是根据配置里的context,上下文来决定的。

(5)文件生成在dist下,而不是一直在js下
output:{
path:path.resolve(__dirname,’./dist’),
filename:’js/[name]-[chunkhash].js’//js文件生成到js文件夹中
},

本文总阅读量