webpack深入了解——多入口、多出口以及html-webpack-plugin

1. 多個入口文件

如果有多個入口文件,該怎么辦呢??? 莫慌,我們可以將entry定義為一個數(shù)組,然后將需要打包的文件的路徑依次寫入,最終打好的包,就會按我們傳入路徑的順序依次排列。

首先,在src目錄下定義一個main2.js,然后在webpack.config.js文件當(dāng)中,將entry屬性改寫一下,如下:

******webpack.config.js文件********

const path = require('path');
module.exports = {
    entry: ['./src/main.js', './src/main2.js'], //多入口的時候,這樣寫
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
    
}

然后,命令行運行 npm run build即可。

2. 多個出口文件

問題又來了,既然有多個入口的文件,那如果有多個出口的文件,怎么辦呢??? 其實,也簡單,首先,我們的entry不能是一個數(shù)組了,因為數(shù)組和對象不一樣,數(shù)組的每一個數(shù)據(jù)沒有名字,所以我們首先要把entry改造成對象,如下:

const path = require('path');
module.exports = {
    entry: {     // 改造成對象之后,長這樣。
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }
    
}

到這里,好像還是多入口對應(yīng)一個出口,我們還需要修改一下filename中的數(shù)據(jù),我們可以寫成這樣filename:'[name].bundle.js',這里的[name]就好比是一個占位符,會把我們多個入口文件的名字替換到這里。最終,代碼如下:

const path = require('path');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    }
    
}

最后,命令行運行npm run build

image.png

這時,打開index.html頁面,什么也沒有? ?? 檢查一下代碼,發(fā)現(xiàn)我們引入的js有問題,<script src='bundle.js'></script>,我們給寫死了,難道需要我們手動寫嗎??? 這會寫瘋的,還好我們webpack有插件的功能,這時我們就需要用到html-webpack-plugin這個插件了,注意,沒有s,沒有s,沒有s,夠三遍了嗎?

3. html-webpack-plugin插件

我們最好是讓dist目錄自己創(chuàng)建,然后index.html也自己創(chuàng)建并且我們打包的多入口文件自動寫好在index.html文件中,這個插件就可以幫我們實現(xiàn)這些。哇~??

1. 首先,本地安裝這個插件,npm i html-webpack-plugin -D

PS E:\goodStudy\webpackStudy> npm i html-webpack-plugin -D
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN html-webpack-plugin@3.2.0 requires a peer of webpack@^1.0.0 || ^2.0.0 || ^3.0.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN webpackStudy@1.0.0 No description
npm WARN webpackStudy@1.0.0 No repository field.

+ html-webpack-plugin@3.2.0
added 7 packages from 4 contributors and audited 79 packages in 3.563s
found 0 vulnerabilities

然后,在webpack.config.js中導(dǎo)入這個模塊,然后在plugins屬性身上創(chuàng)建一個html-webpack-plugin的實例。

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin()
    ]
    
}

引入模塊之后,接著就可以在命令行運行 npm run build了,好激動??

PS E:\goodStudy\webpackStudy> npm run build

> webpackStudy@1.0.0 build E:\goodStudy\webpackStudy
> webpack --mode development

C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\bin\cli.js:231
                                throw err;
                                ^

Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object.<anonymous> (E:\goodStudy\webpackStudy\node_modules\html-webpack-plugin\lib\compiler.js:9:28)
    at Module._compile (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object.<anonymous> (E:\goodStudy\webpackStudy\node_modules\html-webpack-plugin\index.js:10:23)
    at Module._compile (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object.<anonymous> (E:\goodStudy\webpackStudy\webpack.config.js:2:27)
    at Module._compile (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at WEBPACK_OPTIONS (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\bin\convert-argv.js:115:13)
    at requireConfig (C:\Users\Administrator\AppData\Roaming\npm\node_modules\webpack-cli\bin\convert-argv.js:117:6)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! webpackStudy@1.0.0 build: `webpack --mode development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the webpackStudy@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2019-08-17T09_48_59_104Z-debug.log

what the fuck!!?? Cannot find module 'webpack/lib/node/NodeTemplatePlugin'這句話好像是在說,我們沒有本地安裝webpack,好吧。

PS E:\goodStudy\webpackStudy> npm i webpack -D
npm WARN webpackStudy@1.0.0 No description
npm WARN webpackStudy@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ webpack@4.39.2
added 346 packages from 197 contributors and audited 4304 packages in 47.673s
found 0 vulnerabilities

輸入npm run build,又感覺好激動??

> webpackStudy@1.0.0 build E:\goodStudy\webpackStudy
> webpack --mode development

One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:
 - webpack-cli (https://github.com/webpack/webpack-cli)
   The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no): yes

這里被提示,是否安裝webpack-cli,我選的yes

要崩潰了??,再次輸入npm run build

PS E:\goodStudy\webpackStudy> npm run build

> webpackStudy@1.0.0 build E:\goodStudy\webpackStudy
> webpack --mode development

Hash: c2d4b4f7780fbf13548e
Version: webpack 4.39.2
Time: 542ms
Built at: 2019-08-17 5:59:56 PM
          Asset       Size  Chunks             Chunk Names
     index.html  249 bytes          [emitted]
 main.bundle.js   3.84 KiB    main  [emitted]  main
main2.bundle.js   3.82 KiB   main2  [emitted]  main2
Entrypoint main = main.bundle.js
Entrypoint main2 = main2.bundle.js
[./src/main.js] 76 bytes {main} [built]
[./src/main2.js] 49 bytes {main2} [built]
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
        + 2 hidden modules

我擦,成功了??,看一下index.html文件中的內(nèi)容

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
  <script type="text/javascript" src="main.bundle.js"></script><script type="text/javascript" src="main2.bundle.js"></script></body>
</html>

dist文件夾也是自動生成的,實現(xiàn)了我們的想法,雖然有些曲折??

激動夠了,又發(fā)現(xiàn)問題了,這個生成的index.html是個什么玩意兒??,什么也沒有啊,能不能定義一個模板之類的呢? 明確告訴大家,有。這需要用到,我們實例化的html-webpack-plugin這個對象了,我們實例了當(dāng)然要有參數(shù)了,否則,他出來干啥?

1. 首先,這個實例有一個template屬性,這個屬性的值是一個模板的相對路徑,注意是相對路徑。

webpack.config.js文件:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({ // 老鐵這樣寫,沒毛病。
            template: './src/index.html'
        })
    ]
    
}

我們的src目錄下的index.html,內(nèi)容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>hello world</title>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

命令行運行npm run build??

dist文件夾中的index.html,內(nèi)容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>hello world</title>
</head>
<body>
    <div id="demo"></div>
<script type="text/javascript" src="main.bundle.js"></script>
<script type="text/javascript" src="main2.bundle.js"></script>
</body>
</html>

牛逼啊~??,當(dāng)然,還有更牛逼的,我們?nèi)绻胍鎿Qhtml頁面中的title,可以這樣做,首先,在webpack.config.js文件中給new的實例添加一個title屬性,值就是你想要修改的title名,然后,頁面中需要使用模板引擎來占位,格式是這樣的<%=htmlWebpackPlugin.options.title %>,這樣就可以定義頁面的title了

webpack.config.js文件:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: '你好,世界',
            template: './src/index.html'
        })
    ]
    
}

src目錄下的index.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> <%= htmlWebpackPlugin.options.title %> </title>
</head>
<body>
    <div id="demo"></div>
</body>
</html>

運行npm run builddist文件夾中的index.html內(nèi)容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> 你好,世界 </title>
</head>
<body>
    <div id="demo"></div>
<script type="text/javascript" src="main.bundle.js"></script>
<script type="text/javascript" src="main2.bundle.js"></script>
</body>
</html>

世界如此的美好,??

既然這個插件這么牛逼,有沒有清緩存的功能呢? 有,直接在實例化的htmlWebpackPlugin身上添加一個hash:true,就搞定了,這樣我們請求的js文件每次都需要重新加載。

webpack.config.js文件:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            hash: true, //清除瀏覽器加載文件的緩存
            title: '你好,世界',
            template: './src/index.html'
        })
    ]
    
}

dist目錄下的index.html文件:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> 你好,世界 </title>
</head>

<body>
    <div id="demo"></div>
    <script type="text/javascript" src="main.bundle.js?ab65187c0b3b8dd2579d"></script>
    <script type="text/javascript" src="main2.bundle.js?ab65187c0b3b8dd2579d"></script>
</body>

</html>

HtmlWebpackPlugin這個插件,還有壓縮代碼的功能,添加minify屬性,這個屬性當(dāng)中有好多的配置,配置查閱地址。

例:

webpack.config.js文件當(dāng)中添加minify屬性

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            minify: {
                collapseWhitespace: true // 刪除空格
            },
            hash: true,
            title: '你好,世界',
            template: './src/index.html'
        })
    ]
    
}

打包完成后,dist目錄下的index.html文件,如下:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>你好,世界</title></head><body><div id="demo"></div><script type="text/javascript" src="main.bundle.js?ab65187c0b3b8dd2579d"></script><script type="text/javascript" src="main2.bundle.js?ab65187c0b3b8dd2579d"></script></body></html>

牛逼啊?。。??

我又有一個問題,咱們上面這一頓操作,都是打包到了一個HTML頁面中,能不能生成多個HTML文件呢?每個文件引用不同的模板,這能實現(xiàn)嗎? 插件回復(fù):只有你想不到,沒有我做不到??,這里需要用到filename這個屬性,就是告訴webpack我要生成兩個HTML文件,一個名字叫這個,另一個名字叫這個,這時,webpack就懂了。

我們先在src目錄下創(chuàng)建一個index2.html的模板文件,然后webpack.config.js文件,如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename:'index.html',
            hash: true,
            title: '你好,世界',
            template: './src/index.html'
        }),

        new HtmlWebpackPlugin({
            filename:'index2.html',
            hash: true,
            title: 'hello world',
            template: './src/index2.html'
        })
    ]
    
}

打包完成之后,dist的目錄,如下:

image.png

有了filename這個屬性,我們想生成幾個HTML文件都不是問題了,哇哈哈哈~??

那個,我還有最后一個問題,如果我想讓js文件分別打包到對應(yīng)的HTML文件當(dāng)中,怎么辦呢? 好辦,????梢酝ㄟ^chunks屬性,來分別告訴實例對象,你只負(fù)責(zé)添加這個js文件就好,注意chunks是個數(shù)組。

webpack.config.js文件,如下:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: {
        main: './src/main.js',
        main2: './src/main2.js'
    },
    output: {//出口配置
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            chunks: ['main'], // 這個名字,就是入口定義的名字
            filename:'index.html',
            hash: true,
            title: '你好,世界',
            template: './src/index.html'
        }),

        new HtmlWebpackPlugin({
            chunks:['main2'],
            filename:'index2.html',
            hash: true,
            title: 'hello world',
            template: './src/index2.html'
        })
    ]
    
}

dist目錄下,index.html和index2.html文件,內(nèi)容如下:

*********index.html**************

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> 你好,世界 </title>
</head>
<body>
    <div id="demo"></div>
<script type="text/javascript" src="main.bundle.js?98a9bd234d1092828bb9"></script></body>
</html>
*********index2.html***********

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> hello world </title>
</head>
<body>
    <div id="demo2"></div>
<script type="text/javascript" src="main2.bundle.js?3c62ba05c1da8e7f6799"></script></body>
</html>

最后,總結(jié)一下html-webpack-plugin插件中常用的配置:

  • template: '相對路徑',作用:加載對應(yīng)的模板文件;
  • title: '標(biāo)題',作用:在頁面中動態(tài)生成標(biāo)題;
  • hash: true,作用:清除瀏覽器緩存,保證每次都加載最新的數(shù)據(jù);
  • minify: {...},作用:壓縮文件的操作;
  • filename: '生成的文件名',作用:用于定義生成多個HTML文件的文件名;
  • chunks: [入口文件名],作用:將對應(yīng)的文件打入對應(yīng)的HTML文件中。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容