webpack3学习
npm install -g webpack
npm init
npm install --save-dev webpack
npm install -g live-server
npm install webpack-dev-server
-D 等价于 --save-dev
devtool:
devtool:
source-map 独立map
cheap-moudle-source-map 独立
eval-source-map eval js 开发阶段
cheap-moudle-eval-source-map
js压缩
const uglifyjs = require('uglifyjs-webpack-plugin');
plugins:[
• new uglify()
]
HTML打包
npm install --save-dev html-webpack-plugin
const htmlPlugin = require('html-webpack-plugin')
plugins:[
• new uglify({
minify:{
removeAttributeQuotes:true
},
hash:true,
template:'./src/index.html'
})
]
CSS、图片
npm install --save-dev file-loader url-loader
module:{
rules:{
test:/\.css$/,
use:[{
loader:"style-loader" #loader不需要引入plugin才需要
},{
loader:"css-loader"
}]
},{
test:/\.(png|jpg|gif)/,
use:[{
loader:"url-loader",
options:{
limit:5000 #小于这个,会打成base64
}
},{
loader:"css-loader"
}]
}
}
CSS分离
npm install --save-dev extract-text-text-webpack-plugin
const extractTextPlugin = require("extract-text-webpack-plugin");
var website={
publicPath:"http://localhsot"
}
output:{
publicPath:website.publicPath
}
plugins:[
new extractTextPlugin("css/index.css")
]
图片分离
参考:www.github.com/wzsxyz/html-withimg-loader
分离less
npm install --save-dev less
npm install --save-dev less-loader
module:{
rules:[{
test:/\.less$/,
use:[{
loader:"style-loader"
},{
loader:"css-loader"
},{
loader:"less-loader"
}]
},{
test:/\.less$/,
use:extractTextPlugin.extract({
use:[{
loader:"css-loader"
},{
loader:"less-loader"
}],
fallback:"style-loader"
})
}]
}
分离sass
npm install --save-dev node-sass sass-loader
{
test:/\.scss$/,
use:extractTextPlugin.extract({
use:[{
loader:"css-loader"
},{
loader:"scss-loader"
}],
fallback:"style-loader"
})
}
css属性前缀
参考:www.github.com/postcss/postcss-loader
清除无用的CSS
npm i -D purifycss-webpack purify-css
const glob=require('glob');
const PurifyCssPlugin=require("purifycss-webpack");
plugins:[
new PurifyCssPlugin({
paths:glob.sync(path.join(__dirname,'src/*.html'))//找到src下面的所有
})
]
开发和生产依赖的安装
devDependencies:开发依赖
dependencies:生产依赖
安装方式:
npm install 安装全局
npm install --save 安装到dependencies
npm install --save-dev 安装到devDependencies
"scripts":{
"server":"webpack-dev-server --open",
"dev":"set type=dev&webpack" //mac "export type=dev&&webpack"
}
引入第三方类库
const webpack = require("webpack")
plugins:[
new webpack.ProvidePlugin({
$:"jquery"
})
]
watch配置
watchOptions:{
poll:1000 //监测时间
aggregeateTimeout:500 //打包间隔
ignored:/node_modules/,//忽略的
}
webpack优化
new webpack.optimize.CommsChunkPlugin({
name:'jquery', //要抽离的类库
filename:"assets/js/jquery.min.js"//抽离的目标路径
minChunks:2 //最小抽离文件数,一般为2
})
静态资源打包
npm install --save-dev copy-webpack-plugin
const copyWebpackPlugin = require("copy-webpack-plugin")
new copyWebpackPlugin([{
from:__dirname+'src/public',
to:'./public'
}])
...