Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: prerender web component into HTML snippet?

tl;dr: Can I create a fully rendered HTML snippet to include into server-side (Twig) templates?

Basically, I need to convert Webpack entrypoints into rendered HTML. Linked CSS and JS files are OK, if they are not necessary for basic functionality. Ideally, this would support Vue.js components, and integrate with Vue CLI.

So, I have a PHP codebase with a lot of Twig templates rendered server side. I am gradually replacing and adding features with Vue.js; currently this means exporting discreet static JS modules via Webpack entrypoints. This works well for the most part.

Now I want to recreate the site's header. Usually the client displays a brief flash as it loads one of my static modules; this is not acceptable for the header, which needs to be instantly available.

The header does not currently use any dynamic data, although it may in the future. (It would be nice to link to an Ajax library at some point, but the header should at least load all available DOM elements without JavaScript.)

I am looking at the Vue Prerender SPA Plugin, which might do the trick, but it apparently focuses on entire routes. I am not using Vue-Router in this case: I don't need/want an entire route, only a single component. I don't even want an <html> or <body> tag; my top-level tag might be a <div> for example.

Bonus points: how todo as a Vue CLI plugin, for multiple Webpack entrypoints?

Thanks!

like image 951
aljabear Avatar asked Mar 01 '18 16:03

aljabear


1 Answers

if I undestand right you wan to generate a twig template with webpack. I've done this before with ejs and the HtmlWebPackPlugin. In you webpack config something like:

new HtmlWebpackPlugin({
  title: "Twig Entry",
  filename: '../generatedTwigTemplate.twig',
  template: 'twigTemplateTogenerate.ejs',
  inject: 'body'
})

The process is to make the html/twig in the ejs file, run the webpack build with htmlwebpackplugin your css/js assets should get injected and a .twig file should be output ready to use.

like image 62
digital-pollution Avatar answered Oct 07 '22 06:10

digital-pollution