Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables from html-webpack-plugin to pug template

Is it possible to pass a variable to the .pug template loaded by the 'pug-html-loader' which I defined in the 'html-webpack-plugin' before?

webpack.config.babel.js

...

{
  test: /\.pug$/,
  use: [
      {
          loader: 'html-loader'
      },
      {
          loader: 'pug-html-loader',
          options: {
              self: true
          }
      }]
}


...

 plugins: [

        new HtmlWebpackPlugin({
            chunks: ['index'],
            filename: 'index.html',
            template: './src/templates/layout.pug',
            title: 'Welcome',
            file: 'index'
        }),

        new HtmlWebpackPlugin({
            chunks: ['index', 'contact'],
            filename: 'contact.html',
            template: './src/templates/layout.pug',
            title: 'Contact us',
            file: 'contact'
        }),

]

In a layout.html I have defined as follows:

<!doctype html>
<html class="no-js" lang="en">
<head>
    <meta charset="utf-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>

<main>
    ${ require('html-loader!../partials/' + htmlWebpackPlugin.options.file + '.html' ) }
</main>

</body>
</html>

How can I use it to pass all variables - defined in the Webpack plugin for the usage in my PugTemplates and files? The application is supposed to be a simple process for creating simple webpages, which consists of several static pages.

like image 455
Sascha Avatar asked Jul 27 '17 10:07

Sascha


1 Answers

For those that are having trouble with this answer. The solution is to create a templateGenerator

Example:

new HTMLWebpackPlugin({
   inject: true,
   templateParameters: paramGenerator(globals), // <--- Here
   template: '/mytemplate.pug',
}),
import { environment } from '../environment';

export function paramGenerator(globals: () => {[key: string]: any}) {
  return (compilation, assets, assetTags, options) => {
    return {
      compilation: compilation,
      webpackConfig: compilation.options,
      htmlWebpackPlugin: {
        tags: assetTags,
        files: assets,
        options: options
      },
      environment,
      ...globals(),
    };
  }
}

Where globals is a function that returns a simple object that is attached to your global pug scope.

like image 70
Kevin Upton Avatar answered Oct 22 '22 05:10

Kevin Upton