webpack小記

把工做中經常使用的webpack配置,包括loader、plugins、優化等記錄下來,方便學習和查閱。會一直更新本文。javascript

初識webpack

  • 在項目裏安裝 webpack、webpack-cli
  • 在根目錄新建 webpack.config.js
  • webpack4有兩種模式:development、production

entry

  • 入口文件,能夠是對象,數組,字符串。
  • 對象,key是能夠作輸出名字。

output

  • path,輸出目錄,絕對路徑。
  • filename,輸出文件的名字
const config = {
  entry:{
      index:'./index'
  },
  output:{
      filename:'[name].[hash].js',   //[name]是entry裏的key,能夠加hash
      path:__dirname
  } 
};
複製代碼

resolve:

  • alias,設置別名。
//a.js
const help = requrie('../libs/help/a.js');
//b.js
const help = requrie('../../../libs/help/b.js');
//咱們看到用到help裏某個文件時,要找不少層目錄,能夠在配置文件裏寫入別名。
const config = {
    resolve:{
        alias:{
            help:path.resolve(__dirname,"libs/help")
        }
    }
};
//a.js
const help = requrie('help/a.js');
//b.js
const help = requrie('help/b.js');
複製代碼
  • extensions,省略擴展名,js引入時不須要寫擴展名

module

  • noParse,若是肯定一個模塊沒有其餘的依賴,能夠配置這項。能夠提升打包的速度
const config = {
    module:{
        noParse:[/jquery/],
        rules:[
            {
                test:'匹配的文件',
                include:'在哪一個目錄查找',
                exclude:'排除哪一個目錄',
                loader:'use:[{loader}]的簡寫',
                use:[
                    //配置多個loader,從有往左依次執行
                    {
                        loader:"須要的loader",
                        options:{
                            //loader的相關配置
                        }
                    }
                ]
            }
        ]
    }
}
複製代碼
  • rules,是一個規則數組,每一項是一個對象,配置loader。

loader

  • 在webpack裏,全部的文件都是模塊。loader的做用就是把文件轉換成webpack能夠識別的模塊。
ES六、ES七、react
  • babel-loader、babel-core
  • babel-preset-stage-0 編譯ES7
  • babel-preset-2015 編譯ES6
  • babel-preset-react 編譯react
{
    module:{
        rules:[
            {
                test: /\.jsx?$/,
                exclude:/node_modules/,
                include:path.resolve(__dirname,'src'),
                use:{
                    loader:'babel-loader',
                    options:{
                        presets:[
                             'es2015','react'
                        ]
                    }
                }
            }
        ]
    }
}
複製代碼
css、less、sass
  • js裏引入css
  • style-loader,把css放在style標籤裏插入html裏。
  • css-loader,識別css,把css變成一個模塊,能夠根據options配置css模塊化等。
  • less-loader 該loader要和less一塊兒使用。
npm install --save-dev less-loader less
複製代碼
npm install sass-loader node-sass webpack --save-dev
複製代碼
const config = {
    module:{
        rules:[
            {
                test: /\.css$/,
                use: [
                    'style-loader', 
                    {
                        loader:'css-loader',
                        options:{
                            modules:true    //css模塊化
                        }
                    }
                    ]
            },
            {
                test: /\.less$/,
                use: ['style-loader', 'css-loader', {
                    loader:'less-loader',
                    options:{
                        modifyVars:{
                            "color":"#ccc"  //設置變量
                        }
                    }
                }]
            },
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    }
}
複製代碼
圖片等其餘資源
  • js裏引入圖片等資源
  • file-loader,在輸出目錄生成對應的圖片
{
    module:{
        rules:[
            {
                test: /\.(png|jpg|gif)$/,
                use: ['file-loader']
            }
        ]
    }
}
複製代碼
  • url-loader,很像file-loader,把符合大小把圖片生成base64,不符合的生成圖片
{
    module:{
        rules:[
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 10*1024,
                            name: '[path][name].[ext]'
                        }
                    }
                ]
            }
        ]
    }
}
複製代碼
html
  • html-loader 能夠把html頁面中引入的圖片,輸出在相應的輸出目錄
{
    test: /\.(html)$/,
    use: {
        loader: 'html-loader'
    }
}
複製代碼

plugins

  • webpack提供了豐富的插件接口。插件可讓webpack靈活可配置。
  • plugins是一個數組,裏面是每一個插件的實例。
清理文件
const CleanWebpackPlugin = requrie('clean-webpack-plugin');
const config = {
    plugins:[
        new CleanWebpackPlugin(['輸出目錄'])
    ]
}
複製代碼
在html里加入資源
  • html-webpack-plugin 設置html模版,讓入口js加載到相應的html裏,能夠根據參數設置js的位置、順序、是否壓縮、加載哪些js、或者不加載哪些js等功能。
const HtmlWebpackPlugin = requrie('html-webpack-plugin');
const config = {
    plugins:[
        new HtmlWebpackPlugin({
            template:'index.html',  //設置模版
            hash:true,  //添加hash
            filename:'hello.html',  //輸出名字
               
        })
    ]
}
複製代碼
提取css
  • extract-text-webpack-plugin,把想要的css提取到相應的文件裏
  • 爲了兼容webpack4要安裝next版本
  • 須要和loader一塊兒使用
npm i extract-text-webpack-plugin@next -S
複製代碼
//注:此處的[name]生成後爲入口文件的key
const cssExtract = new ExtractTextPlugin('public/[name].[contenthash:8].css');
const lessExtract = new ExtractTextPlugin('public/[name].[contenthash:8].css');
const scssExtract = new ExtractTextPlugin('public/[name].[contenthash:8].css');
const config = {
  module:{
      rules:[
          {
            test: /\.css$/,
            use: cssExtract.extract(['css-loader'])
           },
        {
            test: /\.less$/,
            use: lessExtract.extract({
                use: ['css-loader', 'less-loader']
            })
        },
        {
            test: /\.scss$/,
            use: scssExtract.extract({
                use: ['css-loader', 'sass-loader']	
            })
        }
      ]
  },
  plugins:[
      cssExtract,
      lessExtract,
      scssExtract
  ]  
};
複製代碼
壓縮混淆代碼
  • (uglifyjs-webpack-plugin)[https://github.com/webpack-contrib/uglifyjs-webpack-plugin]
const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
const config = {
  module:{
  plugins:[
      new UglifyjsWebpackPlugin({
        test: /\.js($|\?)/i
      })
  ] 
  } 
};
複製代碼
  • 或者用webpack的生產模式
webpack --mode production
複製代碼
拷貝靜態文件
const CopyWebpackPlugin = require('copy-webpack-plugin');
{
    plugins:[
        new CopyWebpackPlugin([
            {
                from:'./src/test',
                to:'./'
            }
        ])
    ]
}
複製代碼

監聽文件變化

  • webpack定時獲取文件等更新時間,並跟上次保存的時間做對比,不同就是作了修改。
  • poll,每秒鐘詢問的次數
  • aggregateTimeout,監聽變化,多少ms後再執行
const config = {
    watch:true,     //watch爲true時,watchOptions才生效
    watchOptions: {
        ignored:/node_modules/, //忽略目錄
        aggregateTimeout:300,   //監聽變化 300ms後再執行
        poll:1000   // 默認每秒詢問1000次
    }
}
複製代碼

webpack-dev-server

  • webpack-dev-server,本地服務器,監聽文件變化自動刷新瀏覽器等功能。
  • 文檔裏是能夠實現模塊熱更替的,我沒有實現,有好的教程請告訴我,謝謝!
const webpack = require('webpack');
const config = {
    devServer: {
        hot: true, //寫了這項就不會自動刷新,不寫就會自動刷新,知道緣由的請留言,謝謝!
        open: true,
        inline:true
    },
    plugins:[
       new webpack.HotModuleReplacementPlugin() //不寫會報錯,不知道爲何。。。
    ]
}
複製代碼

總結

記錄用到過的webpack loaders、plugins和其餘相關配置。後續還會添加提取共代碼等其餘優化處理。css

參考

相關文章
相關標籤/搜索