《webpack深入与实战》学习笔记

来源:互联网 发布:万网域名cname怎么设置 编辑:程序博客网 时间:2024/05/17 11:59

1.webpack安装和使用

//npm初始化:cnpm init//安装webpack:cnpm install -g webpack --save-dev//打包:webpack test.js test.bundle.js

2.引用css文件时
打包的js文件中引用了css文件时,需要安装css-loader和style-loader

//安装css-loader和style-loader:cnpm install -g css-loader style-loader --save-dev//打包:webpack test.js test.bundle.js --module-bind 'css=style-loader!css-loader'

或者在引用css的时候声明其打包方式

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

3.修改后自动打包

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

–watch:监视文件的修改,修改后自动执行打包
–progress:显示打包进度
–display-modules:显示打包的模块
–display-reasons:显示模块打包的原因

4、webpack基本配置
新建webpack.config.js文件。

module.exports={    entry: './src/js/main.js', //打包入口    output:{        path: '/Users/xxx/workspace/webpack2/dist/js',        filename: 'bundle.js'    }}

在package.json中配置webpack

{  "name": "webpack2",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "webpack":"webpack --config webpack.config.js --progress --display-modules --colors --display-reasons"  },  "author": "xxx",  "license": "ISC"}
//执行webpack.config:cnpm run webpack

entry:[],将不互相依赖的、平行的文件打包到一起;
entry:{},多页面应用程序,output使用[name]、[hash]、[chunkhash]等占位符,否则生成的打包文件会覆盖

module.exports={    entry:{        main: './src/js/main.js',        a: './src/js/a/js'    },    output:{        path: '/Users/xxx/workspace/webpack2/dist/js',        filename:'[name]-[hash].js'    }}

文件hash值可看做文件版本号或者md5值,文件发生更改时hash值也发生变化。
5、在html中引用带hash后缀的文件
打包后的文件若带hash后缀的,因为每次打包生成的文件的hash值都不同,在html中方便地引用这样的文件需要webpack的插件。

//安装插件:cnpm install -g html-webpack-plugin --save-dev

在webpack配置文件中引用插件,并在插件属性中初始化

var htmlWebpackPlugin = require('html-webpack-plugin');module.exports={    entry: {        index: './src/js/index.js',        a: './src/js/a.js'    }, //打包入口    output:{        path: '/Users/xyn/workspace/webpack/dist',        filename: 'js/[name]-[chunkhash].js'    },    plugins:[        new htmlWebpackPlugin({            template: 'index.html',            filename:'index-[hash].html',            inject: 'body',        })    ]}
原创粉丝点击