Webpack 4.X 從入門到精通 - module(四)

概念

webpack中任何一個東西都稱爲模塊,js就不用說了。一個css文件,一張圖片、一個less文件都是一個模塊,都能用導入模塊的語法(commonjsrequireES6import)導入進來。webpack自身只能讀懂js類型的文件,其它的都不認識。但是webpack卻能編譯打包其它類型的文件,像ES6JSXlesstypeScript等,甚至cssimages也是Ok的,而想要編譯打包這些文件就需要藉助loader

loader就像是一個翻譯員,瀏覽器不是不認識這些東西麼?那好交給loader來辦,它能把這些東西都翻譯成瀏覽器認識的語言。loader描述了webpack如何處理非js模塊,而這些模塊想要打包loader必不可少,所以它在webpack裏顯得異常重要。loader跟插件一樣都是模塊,想要用它需要先安裝它,使用的時候把它放在module.rules參數裏,rules翻譯過來的意思就是規則,所以也可以認爲loader就是一個用來處理不同文件的規則

文件目錄

這節課需要用到圖片跟樣式,所以我要按傳統的目錄結構來創建目錄,目錄如下
結構目錄
Webpack 4.X 從入門到精通 - module(四)

處理CSS

所需loader

style-loader   //把處理完的css放到style標籤裏
css-loader     //處理css

安裝

npm i style-loader css-loader -D

index.css文件內容如下:

#box{
    width: 800px;
    height: 500px;
    border: 5px solid #999;
    color: #00f;
    background: green;
}

index.js文件內容如下:

import '../css/index.css';  //兩個點是找上級目錄

通過前面的課程大家要明白,webpack的入口文件是index.js,如果要處理其它類型的文件,就需要在入口文件裏把其它類型的文件導入進來,而在webpack中所有文件都是模塊,所以可以使用require或者import導入其它文件

package.json文件內容如下:

{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "build": "webpack --mode production",
    "dev": "webpack-dev-server --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^1.0.0",
    "html-webpack-plugin": "^3.2.0",
    "style-loader": "^0.21.0",
    "webpack": "^4.16.3",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  }
}

webpack.package.json文件內容如下:

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

module.exports={
    entry:{
        index:'./src/js/index.js',
    },
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'[name].bundle.js'
    },
    plugins:[
        new HtmlWebpackPlugin({
            title:'陳學輝',
            template:'./src/template.html',
            filename:'index.html',
        })
    ],
    devServer:{
        host:'localhost',
        port:1573,
        open:true,
    },
    module:{
        rules:[
            {
                test:/\.css$/,  //以點開始css結尾的文件
                use:['style-loader','css-loader']   //順序不能搞錯
            }
        ]
    },
}   

執行命令npm run dev後就可以看到效果

說明

  1. rules裏的數據類型爲對象,每一個loader都是一個對象
  2. test表示loader要處理什麼類型的文件,這裏用了一個正則去匹配文件類型
  3. use表示要使用哪個loader,它的值是個數組,loader的使用順序是從後往前
  4. 這個loader的意思爲,在入口文件裏找到.css類型的文件,先拿css-loader去處理成瀏覽器認識的css,再拿style-loader把處理後的css放在頁面的style標籤裏

css-loader其它配置:https://www.webpackjs.com/loaders/css-loader/
style-loader其它配置:https://www.webpackjs.com/loaders/style-loader/

單獨提取CSS

執行命令npm run build後,在dist目錄裏只有兩個文件,一個index.bundle.js一個index.html文件,並沒有css文件,同時打開index.html源碼後也沒有發現有css的內容。這是因爲style-loader的作用,它把css一同打包到了js文件裏,js文件在能過DOM動態創建style標籤並添加到頁面裏。所以css的內容已經放到了index.bundle.js裏。
Webpack 4.X 從入門到精通 - module(四)

這種形式只有當文件內容不多的時候可以使用,如果CSS的內容以及JS的內容非常的多,把兩塊都打包到一個文件裏就會增加文件的體積,用戶打開頁面的時候下載速度會受影響,同減肥影響用戶體驗。這就需要把CSS文件單獨拎出來,那需要一個插件來配合loader才能完成

mini-css-extract-plugin

webpack版本需要4.3以上,低版本請使用extract-text-webpack-plugin
使用步驟:
1、安裝

npm i mini-css-extract-plugin -D

2、在webpack.config.js裏引入模塊

const MiniCssExtractPlugin=require("mini-css-extract-plugin");

3、寫入plugins

plugins:[
    new HtmlWebpackPlugin({
        title:'陳學輝',
        template:'./src/template.html',
        filename:'index.html',
    }),
    new MiniCssExtractPlugin({
        filename:'css/index.css'    //文件目錄會放入output.path裏
    }),
]

4、寫入loader

module:{
    rules:[
        {
            test:/\.css$/,
            use:[MiniCssExtractPlugin.loader,"css-loader"]  //代替style-loader
        }
    ]
}

執行命令npm run build後可以看到dist目錄裏已經多了一個css文件夾,這個文件夾裏放了一個index.css文件。打開index.html源碼看到css文件已經通過link標籤引入,這些功能都是mini-css-extract-plugin所做的
Webpack 4.X 從入門到精通 - module(四)
Webpack 4.X 從入門到精通 - module(四)

mini-css-extract-plugin其它配置:https://github.com/webpack-contrib/mini-css-extract-plugin

處理圖片

所需loader

file-loader   //解析地址
url-loader    //把圖片地址解析成base64

安裝

npm i file-loader url-loader -D

index.css文件內容如下:

#box{
    width: 800px;
    height: 500px;
    border: 5px solid #999;
    color: #00f;
    /*background: green;*/

    background: url(../images/img_01.jpg);  //背景改成了圖片
}

index.js文件內容如下:

import '../css/index.css';  //兩個點是找上級目錄

webpack.package.json文件內容如下:

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

module.exports={
    entry:{
        index:'./src/js/index.js',
    },
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'[name].bundle.js'
    },
    plugins:[
        new HtmlWebpackPlugin({
            title:'陳學輝',
            template:'./src/template.html',
            filename:'index.html',
        })
    ],
    devServer:{
        host:'localhost',
        port:1573,
        open:true,
    },
    module:{
        rules:[
            {
                test:/\.css$/,  //以點開始css結尾的文件
                use:[
                    //這是一個loader,如果loader需要給參數,就寫成對象的形式
                    {
                        loader:MiniCssExtractPlugin.loader, //loader是哪個
                        options:{   //所有的配置參數都要放在這個對象裏面
                            publicPath:'../'    //這個表示在css文件裏但凡用到地址的地方在其前面加個目錄'../',這個是爲了能找到圖片
                        }
                    },
                    'css-loader'    //這個loader沒有其它選項就直接寫
                ]
            },
            {
                test:/\.(jpg|png|gif)$/,    //找到三種格式中的任意一種
                use:['file-loader']
            }
        ]
    },
}   

執行命令npm run dev後就可以看到效果

說明

  1. loader既可以寫成字符串的形式,也可以寫成對象的形式。如果這個loader需要給一些配置,那就需要寫成對象的形式,所有的配置放到options
  2. 這裏一定要注意第一個loaderuse屬性,它裏面放的是一個個loader,每個loader的值既可以是對象形式,又可以是字符串形式

file-loader其它配置:https://www.webpackjs.com/loaders/file-loader/

在HTML文件中使用圖片

index.js文件內容如下:

import '../css/index.css';

import img1 from '../images/img_01.jpg';
import img2 from '../images/img_02.jpg';

const loadImg=img=>{
    const newImg=new Image();
    newImg.onload=()=>document.body.appendChild(newImg);
    newImg.src=img;
};

loadImg(img1);
loadImg(img2);

webpack.package.json文件內容如下:

const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const MiniCssExtractPlugin=require("mini-css-extract-plugin");

module.exports={
    entry:{
        index:'./src/js/index.js',
    },
    output:{
        path:path.resolve(__dirname,'dist'),
        filename:'[name].bundle.js'
    },
    plugins:[
        new HtmlWebpackPlugin({
            title:'陳學輝',
            template:'./src/template.html',
            filename:'index.html',
        }),
        new MiniCssExtractPlugin({
            filename:'css/index.css'
        }),
    ],
    devServer:{
        host:'localhost',
        port:1573,
        open:true,
    },
    module:{
        rules:[
            {
                test:/\.css$/,
                use:[
                    {
                        loader:MiniCssExtractPlugin.loader,
                        options:{
                            publicPath:'../'
                        }
                    },
                    "css-loader"
                ]
            },
            {
                test:/\.(jpg|png|gif)$/,
                //use:['file-loader']
                use:[
                    {
                        loader:'url-loader',    //把圖片轉成base64
                        options:{
                            limit:50*1024,  //小於50k就會轉成base64
                            outputPath: 'images'
                        }
                    }
                ]

                //use:'url-loader?limit=50000&outputPath=images'    //loader的另一種寫法,與get請求方式相同
            }
        ]
    },
}   

執行命令npm run dev後就可以看到效果

說明

  1. url-loader的作用是把圖片轉成base64,它同樣可以給配置參數
  2. limit的作用是小於這個值就會轉base64
  3. 只用了url-loader,並沒有用file-loader,說明url-loader裏已經包含了file-loader的功能
  4. loader還可以寫成地址的形式,與get的請求方式相同

Webpack 4.X 從入門到精通 - module(四)
url-loader其它配置:https://www.webpackjs.com/loaders/url-loader/

資料下載:https://pan.baidu.com/s/1tgNtUZHe3oTmVMi96tHTXQ

下一篇:Webpack 4.X 從入門到精通 - loader(五)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章