上一篇博客解说了webpack环境的基础,这一篇解说一些更深切的内容和开辟技能。基础环境搭建就不睁开讲了
一、插件篇
1. 自动补全css3前缀
autoprefixer
官方是如许说的:
Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website
,也就是说它是一个自动检测兼容性给各个浏览器加个内核前缀的插件。
举个栗子:最新的弹性盒模子flux
现实代码:
:fullscreen a {
display: flex
}
插件自动补充后
a {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex
}
结果不言而喻,我们能够更专注于css规划和美化,而不需要花过量的精神都写雷同的外码而加上差别的前缀,也减少了冗余代码。
运用方法:
cnpm install --save-dev autoprefixer postcss-loader
var autoprefixer = require('autoprefixer');
module.exports={
//其他设置这里就不写了
module:{
loaders:[
{
test:/\.css$/,
//在原有基础上加上一个postcss的loader就能够了
loaders:['style-loader','css-loader','postcss-loader']
}
]
},
postcss:[autoprefixer({browsers:['last 2 versions']})]
}
2. 自动天生html插件
html-webpack-plugin
cnpm install html-webpack-plugin --save-dev
//webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports={
entry:'./index.js',
output:{
path:__dirname+'/dist',
filename:'bundle.js'
}
plugins:[
new HtmlWebpackPlugin()
]
}
作用:它会在dist目次下自动天生一个index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webpack App</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
其他设置参数:
{
entry: 'index.js',
output: {
path: 'dist',
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
filename: 'admin.html',
template:'header.html',
inject: 'body',
favicon:'./images/favico.ico',
minify:true,
hash:true,
cache:false,
showErrors:false,
"chunks": {
"head": {
"entry": "assets/head_bundle.js",
"css": [ "main.css" ]
},
xhtml:false
})
]
}
--- header.html ---
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
</body>
</html>
作用:
title: 设置title的名字
filename: 设置这个html的文件名
template:要运用的模块的途径
inject: 把模板注入到哪一个标签后 'body',
favicon: 给html增加一个favicon './images/favico.ico',
minify:是不是紧缩 {...} | false (最新api更改,原来是ture|false 谢谢@onmi斧正)
hash:是不是hash化 true false ,
cache:是不是缓存,
showErrors:是不是显现毛病,
chunks:现在没太邃晓
xhtml:是不是自动毕业标签 默许false
3. 提取款式插件
extract-text-webpack-plugin
官网是这么诠释的
Extract text from bundle into a file.
,把分外的数据加到编译好的文件中
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/public/index.html',
inject: 'body'
}),
new ExtractTextPlugin("[name].[hash].css")
]
}
申明:将css放到index.html的body上面
4. 拷贝资本插件
copy-webpack-plugin
官方如许诠释
Copy files and directories in webpack
,在webpack中拷贝文件和文件夹
cnpm install --save-dev copy-webpack-plugin
new CopyWebpackPlugin([{
from: __dirname + '/src/public'
}]),
作用:把public 内里的内容悉数拷贝到编译目次
参数 | 作用 | 其他申明 |
---|---|---|
from | 定义要拷贝的源目次 | from: __dirname + ‘/src/public’ |
to | 定义要烤盘膛的目的目次 | from: __dirname + ‘/dist’ |
toType | file 或许 dir | 可选,默许是文件 |
force | 强迫掩盖先前的插件 | 可选 默许false |
context | 不知道作用 | 可选 默许 base context 可用 specific context |
flatten | 只拷贝文件不论文件夹 | 默许是false |
ignore | 疏忽拷贝指定的文件 | 能够用隐约婚配 |
5. 全局挂载插件
webpack.ProvidePlugin [webpack内置插件 ]
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}))
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.CommonsChunkPlugin('common.js')
作用: 和上面5个一一对应
当模块运用这些变量的时刻,wepback会自动加载。(区分于window挂载,谢谢@lihuanghe121斧正)
不显现毛病插件
查找相称或近似的模块,防止在终究天生的文件中涌现反复的模块
丑化js 殽杂代码而用
提取大众代码的插件
二、一个完全的栗子
'use strict';
// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
/**
* Env
* Get npm lifecycle event to identify the environment
*/
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';
module.exports = function makeWebpackConfig() {
var config = {};
config.entry = isTest ? {} : {
app: './src/app/app.js'
};
config.output = isTest ? {} : {
// Absolute output directory
path: __dirname + '/dist',
publicPath: isProd ? '/' : 'http://localhost:8080/',
filename: isProd ? '[name].[hash].js' : '[name].bundle.js',
chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
};
if (isTest) {
config.devtool = 'inline-source-map';
} else if (isProd) {
config.devtool = 'source-map';
} else {
config.devtool = 'eval-source-map';
}
config.module = {
preLoaders: [],
loaders: [{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
}, {
test: /\.css/,
loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
}, {
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file'
}, {
test: /\.json$/,
loader: 'json'
}, {
test: /\.scss/,
loader: 'style!css!sass'
}, {
test: /\.html$/,
loader: 'raw'
}]
};
if (isTest) {
config.module.preLoaders.push({
test: /\.js$/,
exclude: [
/node_modules/,
/\.spec\.js$/
],
loader: 'isparta-instrumenter'
})
}
config.postcss = [
autoprefixer({
browsers: ['last 2 version']
})
];
config.plugins = [];
if (!isTest) {
config.plugins.push(
new HtmlWebpackPlugin({
template: './src/public/index.html',
inject: 'body'
}),
new ExtractTextPlugin('[name].[hash].css', {disable: !isProd})
)
}
if (isProd) {
config.plugins.push(
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new CopyWebpackPlugin([{
from: __dirname + '/src/public'
}]),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}))
}
config.devServer = {
contentBase: './src/public',
stats: 'minimal'
};
return config;
}();
三、调试技能
if (isTest) {
config.devtool = 'inline-source-map';
}
作用: 运用source-map能够在debug的时刻看到源代码,轻易 查错