undefinedfix
Sign in

How to modularize webpack EJS?

Wouter edited in Fri, 23 Sep 2022

such as header.ejs :

<div class="header-tpl"><%= title %></div>

header.js :

import header from './header.ejs';
import './header.css';

export default function HeaderTpl(){
    const data = {
        title: 'I am header'
    }
    return {
        header: header(data)
    }
}

These are two unrelated documents, which are listed in the home.ejs :

<%= require('./components/header.ejs')() %>
...

I'll report an error and I can't find the title (of course, because it's not related header.js )What I want to ask is how to write in webpack?

Google's solution:

  1. Write it in the configuration file
const value = {...}
plugins.push(
    new HtmlWebpackPlugin({
      filename: `${value.path}.html`,
      template: path.resolve(__dirname, '../src', `${value.path}.ejs`),
      inject: true,
      chunks: ['common', value.path],
      favicon: './src/assets/img/favicon.ico',
      title: value.text,   // 这里传入了title
      path:value.path,
      minify: {
        collapseWhitespace: true
      }
    })
  )
  1. Import through JS
import HeaderTpl from '../components/header.js';
const header = new HeaderTpl();
$('body').prepend(header.header);

Yes, there's nothing wrong with it, but I prefer it

<%= require('./components/header.ejs')() %>

It is easy to maintain

Excuse me, does a boss know how to configure it more reasonably?

0 Replies