webpack plugin

一、webpack常用的插件安装命令
1、自动快速的帮我们生成HTML

npm install html-webpack-plugin --save-dev

2、样式
我们需要两种loader,css-loader 和 style-loader,css-loader会遍历css文件,找到所有的url(…)并且处理。style-loader会把所有的样式插入到你页面的一个style tag中。

npm install css-loader style-loader --save-dev

3、安装加载器
(babel-loader 进行转码
css-loader 对 css 文件进行打包
style-loader 将样式添加进 DOM 中)

npm install babel-loader css-loader style-loader --save-dev

4、解析sass文件
css预编译程序,还需要添加node-sass来解析sass文件

npm install sass-loader node-sass --save-dev

5、图片编码
图片自动转成base64编码

npm install url-loader --save-dev

6、添加第三方库
添加第三方库(jquery和moment)

npm install jquery moment --save-dev

7、添加ES6的支持

npm install babel-preset-es2015 --save-dev

8、安装转码规则

npm install babel-preset-es2015 babel-preset-react --save-dev

9、安装express的middleware
服务器端使用的是express框架,你还可以直接安装express的middleware,webpack配合express

npm install webpack-dev-middleware --save-dev

10、安装并引用 React 模块

npm install react --save-dev

11、添加react和react-dom

npm install react react-dom --save-dev

12、React 热插拔的加载插件
react-hot-loader 是一款非常好用的 React 热插拔的加载插件,通过它可以实现修改-运行同步的效果,配合 webpack-dev-server 使用更佳!

npm install react-hot-loader --save-dev

13、

npm install --save-dev autoprefixer postcss-loader --save-dev

14、

npm install babel-loader coffee-loader --save-dev

15、

npm install autoprefixer-loader --save-dev

16、

npm install vue --save-dev

17、将项目中package.json依赖的包全部下载到该项目中

npm install -d

二、webpack-plugin

1、 自动补全css3前缀(autoprefixer)
举个例子:最新的弹性盒模型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)
把额外的数据加到编译好的文件中

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)
在webpack中拷贝文件和文件夹

cnpm install --save-dev copy-webpack-plugin
new CopyWebpackPlugin([{
    from: __dirname + '/src/public'
}]),

作用:把public 里面的内容全部拷贝到编译目录

参数作用其他说明
from定义要拷贝的源目录from: __dirname + ‘/src/public’
to定义要烤盘膛的目标目录from: __dirname + ‘/dist’
toTypefile 或者 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')

三、一个完整的例子

'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的时候看到源代码,方便 查错

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值