emaphp / underscore-template-loader

A Underscore and Lodash template loader for Webpack
MIT License
104 stars 24 forks source link

Question about Requiring the Engine #19

Open MattSurabian opened 8 years ago

MattSurabian commented 8 years ago

Thanks for a great webpack plugin!

I recently refactored some code using this loader to no longer require the use of lodash's templateSettings.imports (and thus the engine config property) and was surprised to see how much that reduced the final size of the project's build and went digging. Wondering if @kmck or others could shed some light on this chunk of code. This was made as part of the PR that allowed support for lodash's template settings imports and I'm just curious why supporting that means the entirety of the lodash engine needs to be loaded into the final webpack bundle? Is it because the templates can't be fully compiled and stored until runtime or something?

My knee jerk reaction was to try and find a way to reduce the need for the entire engine to be loaded but pretty quickly realized I didn't have full context for the inner workings. Anyway, curious to learn a little more from yall.

kmck commented 8 years ago

Sure! So, without the use of the engine option, any references to _ within templates use whatever window._ is in the browser. If you're not already requiring lodash or underscore globally in your project, it might not be defined, so those _.whatever functions won't work. That's something that could happen if you do <%- someVar %>, which would normally try to use _.escape.

If you don't need _.templateSettings.imports and want to keep the bundled size down, you might not want to bother with the engine option in the first place. The idea is that _.templateSettings.imports, so being able to use the same thing to define imports for the templates is convenient.

Now that I'm looking at it again, I could see how you might prefer to specify the object to use for imports without requiring the whole engine if you weren't already requiring it for your project. It's probably possible to replace this with something other than _.templateSettings.imports.

MattSurabian commented 8 years ago

Ultimately yeah, I just removed the engine attribute once I had removed the need for templateSettings and everything was chill.

I guess my assumption was that this plugin compiled the templates into functions which returned strings during build time using whatever engine controlled _ but that at runtime _ was no longer necessary and thus the engine wouldn't need to be in the final bundle at all.

kmck commented 8 years ago

Yeah, that may or may not be true depending on what's going on inside your templates. The more I think about it, the more I like the idea of being able to still get some of the nice things from lodash/underscore inside the templates without using the whole library. I might take a crack at refactoring a little bit to make that work, if someone else doesn't do it first.