天天看點

webpack 項目使用 html-webpack-plugin(3)

html-webpack-plugin 這個插件的功能是将 html 檔案打包,在上一篇的部落格中我們使用webpack-server将webpack項目使用本地的項目打開如:loalhost:3000

webpack 項目使用 html-webpack-plugin(3)

 但是最終顯示的結果如上,顯示這個目錄下面的檔案,并不是我們想要的index.html頁面,這也就是因為我們的html 參與項目的打包。那麼如何将項目打包,才能實作首頁是我們的index.html,這就需要一個插件:html-webpack-plugin

我們繼續之前的項目:

1. 下載下傳 html-webpack-plugin

       cnpm i html-webpack-plugin -D

webpack 項目使用 html-webpack-plugin(3)

 2.修改 webpack.config.js

const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin'); //導入,在記憶體中自動生成 index 頁面
const htmlPlugin=new HtmlWebpackPlugin({
     template:path.join(__dirname,'./src/index.html'),
     filename:'index.html'
});



module.exports={
    mode:'development',
    plugins:[
        htmlPlugin
    ]
}      

3.重新運作

npm run dev

webpack 項目使用 html-webpack-plugin(3)

 我們可以看到現在的localhost:3000 不再是檔案的目錄了,變成了項目的首頁,這也就是我們的html-webpack-plugin的作用

4.需要注意的是在使用了html-webpack-plugin插件之後 我們的index.html頁面會自動的引入相關的js

webpack 項目使用 html-webpack-plugin(3)

 那麼我們就不需要手動的引入main.js了

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>hello</title>
    </head>
    <body>
       <h1>Hello World</h1>
    </body>
</html>