DEV Community

Discussion on: Vue Application as a Wordpress Plugin

Collapse
 
angelinetran profile image
Angeline Tran

Nice! Thanks for this! I extended your code to use glob and regex so I could keep the hash.

function get_hashed_file($filename)
{
    $regex = '/\/[\w-]+\.[\w-]+.*/i';
    $fileWithHash = glob(dirname(__FILE__) . '/dist/js/' . $filename . '.*.js')[0];
    preg_match($regex, $fileWithHash, $matches);
    return $matches[0];
}

//Register scripts to use
function func_load_vuescripts()
{
    $file = plugin_dir_url(__FILE__) . 'dist/js' . get_hashed_file('app');
    wp_register_script('wpvue_vuejs', $file, ['wpvue_vuejs1'], filemtime($file));

    $file2 = plugin_dir_url(__FILE__) . 'dist/js' . get_hashed_file('chunk-vendors');
    wp_register_script('wpvue_vuejs1', $file2, [], filemtime($file2));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonyhayama profile image
Jony Hayama

Awesome!!

Although - if you allow me to share a small thought - if you are using the hash, you do not need filemtime. I mean, the purpose of the hash is to avoid whatever new code you create from being cached...I guess it's a way to make the browser "think" it's a new file... WordPress handles this is by adding ?v=XXX to the end of your path where XXX is whatever you pass as the last argument for the wp_register_script function.

So, to make your code just a smidge more performant, I would replace filemtime with null (or simply remove the argument) :D