一、webpack基本介绍
**1-1**webpack基本介绍
webpack的概念和作用
模块打包器
代码分割
代码文件打包
loader加载
commonjs规范
模块热更新
适用于大型项目**1-2**webpack安装和命令
安装
npm install webpack --save-dev
例子:
新建hello.js
执行命令 webpack hello.js hello.bundle.js
,会生成hello.bundle.js
文件,观察文件中的内容,可以看到webpack
在文件中生成了许多其他代码
新建world.js
并在hello.js
文件中require('./world.js')
,再执行命令webpack hello.js hello.bundle.js
,观察hello.bundle.js
文件中的内容
新建style.css
,在样式表中随便新建几行样式html,body{background: #f00;}
,在hello.js
文件中require('style-loader!css-loader!./style.css')
,执行命令webpack hello.js hello.bundle.js
(注意:用webpack
加载css
需要用到css-loader
,行内样式需要用到style-loader
。安装loader npm install css-loader style-loader --save-dev)
css-loader
用来将style.css
打包到hello.bundle.js
文件中,使webpack
能处理.css文件,如果将css-loader
处理后的文件,引入到页面中后(在这个例子中引入页面的是hello.bundle.js
),style-loader
则会将style.css
中的样式以<style></style>
的形式插入到head
中
如果在页面中没有加载这两个loader
也可以在命令行中直接加载loader
webpack hello.js hello.bundle.js --module-bind 'css=style-loader!css-loader'
输入webpack
可以查看webpack
中有哪些配置项
webpack hello.js hello.bundle.js --watch
用来监听文件,如果文件有变化则自动编译打包
webpack hello.js hello.bundle.js --progress
用来查看打包的进度
webpack hello.js hello.bundle.js --display-module
用来查看打包的模块
webpack hello.js hello.bundle.js --display-reson
用来查看打包的原因
二、webpack基本配置
- 2-1建立项目的webpack配置
例子:
在webpack-demo目录下新建以下文件
webpack-demo
-dist
--js
-src
--script
--style
-index.html
-package.json
-webpack.config.js
webpack.config.js
module.exports = {
entry: './src/script/main.js',//入口文件
output: {
path: './dist/js',//输出路径
filename: 'bundle.js'//输出文件名
}
}
运行 webpack 会在dist下的js目录下生成bundle.js
可在pack.json的script字段中添加配置webpack
"scripts": {
"webpack":"webpack --config webpack.config.js --progress --display-modules --colors --display-reasons"
},
2-2
webpack
配置的entry
和output
entry
是入口文件
①entry
可以是一个数组entry:[‘a.js’,’main.js’]
②entry
可以是一个对象用于多入口的情况下
entry:{
page1:'./page1'
page2:['entry1.js','entry2.js']
}
在entry
是多入口的情况下,output也应该是多个输出 filename
有三个可选参数 [name]
、[hash]
、[chunkhash]
output: {
path: _dirname+'/built',//输出路径
filename: '[name].js'//输出文件名
}
注意,在不同的版本下可能会报路径不是绝对路径的错误,解决办法为
var path = require('path');
module.exports = {
entry: [url('src/script/main.js'), url('src/script/a.js')],
output: {
path: url('./dist/js/'),
filename: 'bundle.js'
}
}
function url(url) {
return path.resolve(__dirname, url)
}
三、生成项目中的html文件
- 3-1自动化生成项目中的html文件(上)
安装
html-webpack-plugin(这里有个坑就是,如果在全局安装webpack,在运行npm run webpack之前需要运行 npm link webpack)
自动生成html的意义在于,html中引用的js文件好多都是webpack打包之后生成的,生成的文件名和目录都有可能改变,这个时候不能手动来修改每一个变动的路径,太耗时,这个时候就要通过html-webpack-plugins这个插件来自动在html中生成对js的引用
在webpack.config.js中加入plugins配置项
var htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: './src/script/main.js',
a: './src/script/a.js'
},
output: {
path: