0

Simple question, is it possible to write a Babel plugin that receives raw file contents and returns a compiled string to Babel before any of those contents are parsed by Babel to AST?

Background

I'm creating a polymorphic React application that needs to compile an HTML template to JS on the server and in the browser.

I use React Templates to create parallel view files alongside react component files, such as this:

components/layout/layout.component.js
components/layout/layout.template.html

This is useful to me since I often need to give designers access to component templates. Then within my compnent file:

import template from './layout.template.html';

class Layout extends React.Component {
  // code
  render(){
    return template.call(this);
  }
}

This works client side fine because I compile with webpack. There's an existing Webpack loader that will take the html contents and use React Templates to transform to Javascript. With webpack, however, you get direct access to the file contents so you can piggyback on the compilation done by the React Templates module (see loader).

Problem is, if I use ReactDomServer.renderToString to render on the server (not Webpack compiled), the impport call above obviously won't import the compiled template.

Is it possible to do something with Babel that is analogous to Webpack, ie compile a file before it is parsed to AST?

The alternative would be writing a task that would compile the template files before the server is run, and then importing the compiled file. This solution leaves a lot of cruft.

twernt
  • 20,271
  • 5
  • 32
  • 41
Eric H.
  • 6,894
  • 8
  • 43
  • 62

1 Answers1

1

babel-plugin-webpack-loaders is likely your best bet in this case.

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
  • Very interesting. I'll give it a shot with react templates loader and accept the answer if I get it to work. – Eric H. Mar 28 '16 at 15:26
  • Seems like this is limited now to a few plugins. I'm curious to see if we can make it work for the general case. Here is the issue I created to pursue: https://github.com/istarkov/babel-plugin-webpack-loaders/issues/62 – Eric H. Mar 28 '16 at 21:24