Last active
February 24, 2022 16:10
-
-
Save tgeorgel/3d90b1feb3fed9f73ab817a96465368f to your computer and use it in GitHub Desktop.
Add Laravel Mix versionning (mix-manifest.json) to Wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (! function_exists('mix')) { | |
/** | |
* Get the path to a versioned Mix file. | |
* | |
* @param string $path | |
* @return \Illuminate\Support\HtmlString|string | |
* | |
* @throws \Exception | |
*/ | |
function mix(string $path) | |
{ | |
$dist_uri = get_stylesheet_directory_uri() . '/dist'; | |
$dist_path = get_stylesheet_directory() . '/dist'; | |
if (! Str::startsWith($path, '/')) { | |
$path = "/{$path}"; | |
} | |
$manifestPath = $dist_path . '/mix-manifest.json'; | |
if (! file_exists($manifestPath)) { | |
throw new Exception('The Mix manifest does not exist.'); | |
} | |
$manifest = json_decode(file_get_contents($manifestPath), true); | |
return new HtmlString($dist_uri . $manifest[$path]); | |
} | |
} | |
add_action('wp_enqueue_scripts', function () { | |
wp_enqueue_style('my_theme', mix('/css/app.css')); | |
wp_enqueue_script('my_theme', mix('/js/app.js')); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mix = require('laravel-mix'); | |
const assetDir = 'resources/assets'; | |
const distDir = './dist'; | |
require('laravel-mix-copy-watched'); | |
// Configure mix/webpack | |
mix.setPublicPath(distDir) | |
// Set options | |
mix.options({ | |
fileLoaderDirs: { | |
images: `${assetDir}/images`, // to load images in scss using url('../images/pic.png') | |
} | |
}); | |
// Compile assets | |
mix.js(`${assetDir}/scripts/app.js`, `${distDir}/js`) | |
.sass(`${assetDir}/styles/app.scss`, `${distDir}/css`) | |
.options({ | |
processCssUrls: false, | |
}) | |
.version() // this is important to generate mix-manifest.json | |
// Copy images in dist folder | |
mix.copyWatched('resources/assets/images/**/*.{jpg,jpeg,png,gif,svg}', 'dist/images', { base: 'resources/assets/images/' }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment