webpack学习笔记啊(幕课)

基础配置总结

  1. webpack hello.js hello.bundle.js打包命令参数

    1. --config filename : 指定其他名称做配置文件
    2. --watch / -w : 监听文件改动,自动编译(速度快)
    3. -d : 开启(生成)source maps (用来调试)
    4. -p : 生产环境下编译(压缩)
    5. --progress : Print compilation progress in percentage
    6. --display-modules : Display even excluded modules in the output
    7. --display-reasons : Display reasons about module inclusion in the output
    8. 可组合使用:webpack -wdp

  1. entry 入口文件三种方式:

    入口文件:用来引入html文件所需要的资源

    1. entry: './src/app.js' :单文件入口
    2. entry: ["./entry1", "./entry2"] : 多个不相关文件入口,打包到一起
    3. 多个模块文件入口
      entry: {
              page1: "./page1",
              page2: ["./entry1", "./entry2"]
      }
      
  2. output 出口文件三个占位符

    {
      entry: {
        app: './src/app.js',
        search: './src/search.js'
      },
      output: {
        filename: '[name].js',
        path: __dirname + '/build'
      }
    }
    
    1. [name] 以模块名字代替,即入口文件定义的key
    2. [hash] 本次打包编译的哈西值
    3. [chunkhash] 相应模块的哈西值,根据md5产生,再次打包只有改变的模块的哈西值会变

  1. loaders三种使用方式

    * webpack默认只支持javascript文件
    *需要用加载器(loader)
    *loader类似一种转化器, 它可以把一个东西,转成另一个

    1. 在引入文件时 require:
      style-loader!css-loader!./style.css
      从右向左执行,不可颠倒顺序,不要丢掉最后一个!
    2. 通过CLI配置(在命令行中):
      webpack --module-bind jade --module-bind 'css=style!css'
      通过参数--module-bind绑定
    3. 通过配置文件配置:
      {
          module: {
              loaders: [
                  { test: /\.jade$/, loader: "jade" },
                  // => "jade" loader is used for ".jade" files
      
                  { test: /\.css$/, loader: "style!css" },
                  // => "style" and "css" loader is used for ".css" files
                  // Alternative syntax:替代语法
                  { test: /\.css$/, loaders: ["style", "css"] },
              ]
          }
      }
      
  2. loader传递查询参数的两种方式:

    1.在loader后面跟?再跟一个参数,类似get请求 2.在配置文件中用query属性加参数

    1. CLI (在命令行中)
      webpack --module-bind "png=url-loader?mimetype=image/png"

    2. 在 require 中:
      require("url-loader?mimetype=image/png!./file.png");

    3. 在配置文件中(有两种方式):

      1. ?
        { test: /\.png$/, loader: "url-loader?mimetype=image/png" }
      2. 通过 query
        {
            test: /\.png$/,
            loader: "url-loader",
            query: { mimetype: "image/png" }
        }
        

  1. webpack-dev-server 三种配置方法

    1. 在命令行启动 : webpack-dev-server
      常用参数:
      1. webpack-dev-server --port 8088 端口号
      2. webpack-dev-server --inline 改变完代码以后,自动刷新浏览器
      3. webpack-dev-server --hot 热重载(局部更改)
        webpack-dev-server --port 8088 --inline --hot
    2. 把参数写到webpack.config.js配置文件中:
      output:{
          ...
      },
      devServer: {
          port: 8088,
          inline: true
      }
      
    3. 把运行命令放到package.json文件:
      {
        "name": "test",
        "version": "1.0.0",
        "description": "",
        "main": "index.js", 
        
        "scripts": {
          "dev": "webpack-dev-server --inline --hot --port 8088"
        },
        
        "author": "",
        "license": "ISC",
        "devDependencies": {
            ...
        }
      }
      
      终端运行: npm run dev
      

常见报错:listen EACCES 127.0.0.1:8080 此端口号已经被监听过了(端口号被占用)


webpack.config.js

  1. 基础

var webpack=require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports={
    entry:{
    	admin:'./entry.js'
    },
    output:{
    	path:__dirname + '/bundle',
    	filename:'bundle.js'
    },
    devtool:'source-map',
    module:{
    	loaders:[
    		{test:/\.css$/,loader:['style-loader','css-loader']}
    	]
    },
    resolve:{
        extensions:['.js','.css','.jsx']  //自动补全识别后缀
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: __dirname + "/app/index.tmpl.html" //根据此模版生成HTML文件
        }),
        new webpack.HotModuleReplacementPlugin()
    ],
    devServer:{    //打包的文件临时生成在内存中
        contentBase:"./",
        historyApiFallback:true,
        inline:true,
        hot:true
    }
};
  1. 较完整

var webpack=require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path=require('path');

module.exports= {
    // context:__dirname,  //上下文环境

    entry:{  //入口文件:用来引入html文件所需要的资源
    	main:'./src/script/main.js'
    	// a:'./src/script/a.js',
    	// b:'./src/script/b.js'
    },
    devtool:'source-map',   //直接生成source-map 等于 webpack -d
    output:{
    	path:__dirname + '/dist',
    	filename:'js/[name]-[chunkhash].js'
       // ,publicPath:'http://cdn.com'      //上线后地址,配置此参数后会把所有引用的地址替换为该参数值开头
    },

    devServer:{
        port:8088,
        inline:true,
        hot:true
    },

    module: {
        noParse:[/jquery/], //不要分析与RegExp或RegExps数组匹配的文件。
        loaders:[
            {
                test:/\.js/,   //匹配规则
                loader:'babel-loader',  //
                // exclude: path.resolve(__dirname,'node_modules'), //使用绝对路径字符串或者使用正则
                exclude: /node_modules/,          //排除 , 使用正则
                // exclude: __dirname+'/node_modules',  //排除
                include:/(src|script)/, //仅包含

                query:{   //给此loader指定查询参数
                    presets:['latest']  //给babel-loader指定处理js特性插件
                }
            },
            {
                test:/\.css$/,
                // loader:'style-loader!css-loader',
                loaders:['style','css']    //loaders写法 '-loader'默认可以用省略
            }
        ]
        // rules: [{
        //
        //     test: /\.css/,
        //     use: [
        //         {loader:'style-loader'},
        //         {loader:'css-loader'},
        //         {
        //             loader: 'postcss-loader',
        //             options: {plugins: function () {return [require('autoprefixer')];}}
        //         }
        //     ]
        // }]
    },
    plugins:[
        new HtmlWebpackPlugin({
            filename:'index.html',  //生成的主文件名称
            template:"index.html",  //根据此模版文件生成
            inject:'body',        //引入js文件的位置
            title:'webpack is good',  //自定义一个属性可以在index.html中访问使用
            date:new Date(),          //自定义一个属性可以在index.html中访问使用
            minify:{      //压缩
                removeComments:true  //删除注释
                //,collapseW hitespace:true //删除空格和换行
            }
        }),
        // new HtmlWebpackPlugin({ //多次配置此插件可以分别生成多个页面文件
        //     filename:'a.html',
        //     template:"index.html",
        //     inject:'false',
        //     title:"this is a.html",
        //     chunks:['main','a']  //需要引入的js模块
        // }),
        // new HtmlWebpackPlugin({
        //     filename:'b.html',
        //     template:"index.html",
        //     inject:'false',
        //     title:"this is b.html",
        //     excludeChunks:['main','a']  //要排除引入的js模块,其余都会引入
        // })
        // ,
        // new webpack.LoaderOptionsPlugin({
        //     options:{ postcss: [ require("autoprefixer")( {browsers: ["last 5 versions"]} ) ] }
        // })
    ],
};

应用例子:

  1. 定制开发环境和产品环境:

    开发环境快速打包,产品环境压缩打包:
    webpack.config.js :
    var webpack=require('webpack');
    var args = require('node-args'); //可读取命令运行时所传入的参数
    var config={
        entry:['./index.html'],
        output:{
            path:__dirname+'/dist',
            filename:'[name].bundle.js',
            publicPath:'/dist/'
        },
        plugins:[],
        module:{
            loaders:[{
                test:/\.js/,
                loader:'bebel',
                include:__dirname,
                exclude:/node_module/
            }]
        }
    };  
    
    ******
    if(args.minify){
        congif.plugins=[
            new webpack.optimize.UglifyJsPlugin({
                compress:{
                    warnings:false  //禁止出现警告
                }
            }),
            new webpack.optimize.OccurenceOrderPlugin();  //优化所有模块的id,使文件更小
        ];
    }
    ******
    module.exports = config;
    
    package.json :
    "scripts": {
        "start": "webpack-dev-server --progress --colors --hot --inline --watch"
        "builde":"webpack --progress --colors --minify"
    }
    
    开发环境执行:webpack
    生产环境执行:npm run builde
    
  2. loaders

    1. css自动添加兼容前缀:
      var HtmlWebpackPlugin = require('html-webpack-plugin');
      
        rules: [{
           test: /\.css/,
           use: [
               {loader:'style-loader'},
               {loader:'css-loader'},
               {
                   loader: 'postcss-loader',
                   options: {plugins: function () {return [require('autoprefixer')];}}
               }
           ]
       }]
      
posted @ 2017-09-07 17:22  杨旺  阅读(234)  评论(0编辑  收藏  举报