iansinnott / react-static-webpack-plugin

Build full static sites using React, React Router and Webpack (Webpack 2 supported)
MIT License
155 stars 24 forks source link

Find and replace strings in HTML files #77

Open samny opened 7 years ago

samny commented 7 years ago

Hi, have the need to be able to replace some contents in the resulting HTML after they're generated. I tried "string-replace-webpack-plugin" and "html-replace-webpack-plugin" but could not get them to work. Any ideas how to accomplish this?

iansinnott commented 7 years ago

Well, off-hand my first thought is to just do it on the CLI in a post build hook. I.e. within package.json you can add postbuild to the scripts section and it will run right after every build. In that command you can use use sed (or any other CLI replacement tool) to replace text within the files and write them back to the same place. For example:

cat ./build/index.html | sed 's/Matched/Replaced/' > ./build/index.html

Of course this is just using unix to your advantage rather than doing anything with javascript.

What exactly is the use case here? Why not modify your template file and just generate the HTML you will want in the end?

samny commented 7 years ago

Thanks @iansinnott, I will try out your suggestion.

Sorry, I should have explained my use-case. I'm working on a site that has most pages rendered by Django but also some React SPA pages. To be able to use some common presentational components across, I would like to generate them as partials with template variables instead of content. The main problem I found is that React HTML encodes all quotes etc. and since I found no way of changing Reacts behaviour my idea was to replace all the encoded entities back to what they need to be (ie. replace " with "). Also in the case of partials I need to get rid of the html doctype.

iansinnott commented 7 years ago

Ah, interesting. I hadn't thought of that use case. Yeah you could still use sed for this, but you could also use dangerouslySetInnerHTML on react components in order to bypass its character escaping. I guess that would only work for inner html though, and not attributes...

If you have a CLI tool to unescape HTML you might be able to simply run the whole HTML file through that program.