Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

header - how to include loaders in webpack?

I am trying to include Header.html and also footer.html inside index.html. Because I am going to use these two files as common for all the pages. As my research webpack is not allowing to import files as

<!--#include file="header.html"-->

I've tried in grunt i was working fine . But how to do in webpack

this is my webpack version details

"name": "webpack-boilerplate",
"version": "1.0.0",

here is what i tried... in my webpack.config.js file

{ 
   test: /.html$/, 
   loader: 'html-loader' 
 }

in my index.html file

<body>
    require("html-loader!./file.html");
    <div class="banner">
        <h3>Banner 1</h3>
    </div>
    <div class="banner banner2">
        <h3>Banner 2</h3>
    </div>
</body>

but its showing in page enter image description here

and this not for react. This is only for website and normal html..

so how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

html-webpack-plugin supports templating with variables.

You can define the variables in your webpack.config.js

new HtmlWebpackPlugin({
    template: './src/index.html',
    header: '<h1>hello world</h1>',
    fotter: '<b>Footer</b>'
}),

And put them in place in your index.html like so:

<html>
    <head></head>
    <body>
        <%= htmlWebpackPlugin.options.header %>
        <!-- all your standard template here -->
        <%= htmlWebpackPlugin.options.footer %>
    </body>
</html>

To load the header and footer from normal HTML files requires an additional step and we use the built in fs node package for this (you don't have to install it).

let fs = require('fs');

const header = fs.readFileSync(__dirname + '/header.html');
const footer = fs.readFileSync(__dirname + '/footer.html');

module.exports = {

    // all of your normal config

    plugins: [
      new HtmlWebpackPlugin({
        template: './src/index.html',
        header: header,
        footer: footer,
      })
     ]
});

Now when you run webpack your HTML file will be injected in the positions you specified with the content of your header and footer files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...