I'm using Webpack with the CleanWebpackPlugin, but I use an index.php. So HtmlWebpackPlugin isn't an option. I found a different plugin called WebpackManifestPlugin. This creates a file with the files and their hash called manifest.json. It looks like this:
{
"main.js": "css.d915ef.js",
"main.css": "main.d915ef.css"
}
But how do I use this in my head?
<link rel="stylesheet" type="text/css" href="dist/main.css">
Because this doesn't work.
Use that function in php script
function asset($asset_name)
{
$manifest = file_get_contents("./manifest.json");
$manifest = json_decode($manifest, true); //decode json string to php associative array
if (!isset($manifest[$asset_name])) return $asset_name; //if manifest.json doesn't contain $asset_name then return $asset_name itself
return "/dist/" . $manifest[$asset_name];
}
It will read and parse manifest.json
and replace "main.js"
with "css.d915ef.js"
You can use asset()
function while generating yout html, like this:
<link rel="stylesheet" type="text/css" href="<?php echo asset("main.js"); ?>">
Please, be aware, that file_get_contents("./manifest.json")
will only work correctly if your php script and manifest.json
is in the same folder. If not - you need to provide correct path to manifest.json
here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With