前言:在6月份的时候写了一个关于vue-cli的webpack探究,当时似懂非懂,现在回过头来,感觉还是欠缺不少,这次看了技术胖的博客,感觉受益匪浅
技术胖博客
1:webpack介绍
webpack 模块打包机
目的:分析你的目录接口,找到JavaScript模块以及其他一些浏览器不能直接运行的拓展语言,将其打包和转换为合适供浏览器使用的格式。webpack还有优化功能
打包:多个js文件打包为一个文件
2:入口与出口文件
webpack.config.js 这是webpack的配置文件。
module.exports={
entry:{} //入口文件
output:{} //出口文件
module:{} //模块,负责加载css,js等转换压缩
plugins:[], //插件
devServer:{} //负责服务器搭建
}
3:css打包
webpack是为了把所有打包为一个js,用来减少http请求数量。
这里就要用到loaders配置
解析css 余姚两个包 style-loader,css-loader
style-loader:处理css中url
css-loder:处理插入css style的标签
写在webpack中的module中
module:{
rules:[
{
test:/\.css$/,
loader:['style-loader','css-loader']
}
]
}
ps:写法有多种,这是常见的一种
4:js代码的压缩
uglifyjs-webpack-plugin(JS压缩插件,简称uglify)
在webpack.config.js中引入
const uglify = require(“uglifyjs-webpack-plugin”)
在module中的plugins也要new一个uglify对象
plugins:[
new uglify()
]
由于开发环境和生产环境不同,在开发环境中对js是不进行压缩的,所以一般在
webpack.config.js外还会有两个js文件dev.js,pro.js分别使用不同的js配置
5:打包html文件
html-webpack-plugin
在webpack.config.js中引入它
const htmlPlugin = require(‘html-webpack-plugin’);
在plugins中进行引入配置
new htmlPlugin({
minify:{
removeAttributeQuotes:true
},
hash:true,
template:'./src/index.html'
})
6:css中图片处理
file-loader,url-loader
file-loader:解决引入路径问题
url-loader:如果图片过多会发出多个http请求,url-loader把图片变成图片编码,生产dataURl
如果图片较大,编码会消耗性能。因此url-loader提供了一个limit参数,小于limit字节的文件会被转为DataURl,大于limit的还会使用file-loader进行copy
module:{
rules:[
{
test:/\.(png|jpg|gif)/,
use[{
loader:'url-loader',
options:{
limit:500000
}
}]
}
]
}
7:css分离和图片路径处理
extract-text-webpack-plugin
引入
const extractTextPlugin = require(‘extract-text-webpack-plugin’);
同上还要在plugins里面设置
new extractTextPlugin(‘…’);
module:{
rules: [
{
test: /\.css$/,
use: extractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},{
test:/\.(png|jpg|gif)/ ,
use:[{
loader:'url-loader',
options:{
limit:500000
}
}]
}
]
},
虽然分离出css,但是css的路径有很多问题,可以使用
publicPath解决,在output中设置publicPath
//出口文件的配置项
output:{
//输出的路径,用了Node语法
path:path.resolve(__dirname,'dist'),
//输出的文件名称
filename:'[name].js',
publicPath:website.publicPath
},
8:处理html中的图片
在HTML页面中会使用img标签,用webpack插件 html-withimg-loader解决
配置loader
{
test: /\.(htm|html)$/i,
use:[ 'html-withimg-loader']
}
9:css3 自动添加前缀
PostCSS插件
postcss.config.js在根目录中
module.exports = {
plugins: [
require(‘autoprefixer’)
]
}
引入autoprefixer插件,自动添加前缀
然后在loader中配置
{
test: /\.css$/,
use: extractTextPlugin.extract({
fallback: 'style-loader',
use: [
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
})
}
10:webpack中的babel
babel是什么
babel是一个编译js的平台,转义es6,es7,jsx的扩展语言
babel-core babel-loader babel-preset-es2015 babel-preset-react
这是babel的npm包
在webpack中配置babel方法
{
test:/\.(jsx|js)$/,
use:{
loader:'babel-loader',
options:{
presets:[
"es2015","react"
]
}
},
exclude:/node_modules/
}
还要在根目录下新建.babelrc文件,并且配置
{
“presets”:[“react”,”es2015”]
}
11:webpack打包之后的调试
Source Maps
配置
module.exports = {
devtool: ‘eval-source-map’,
entry: __dirname + “/app/main.js”,
output: {
path: __dirname + “/public”,
filename: “bundle.js”
}
}