DEV Community

Discussion on: Vue Application as a Wordpress Plugin

Collapse
 
jonyhayama profile image
Jony Hayama

Cool stuff!

I would like to contribute with a quick piece of code to handle the enqueue_script cache and filenameHashing issue.

We can use the filemtime on the func_load_vuescripts function a to handle files being cached:

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

  $file = plugin_dir_url(__FILE__) . 'dist/js/chunk-vendors.js';
  wp_register_script('wpvue_vuejs1', $file, [], filemtime($file));
}
Enter fullscreen mode Exit fullscreen mode

I've also added the chunck-vendors as a dependency on wpvue_vuejs so it gets enqueue automatically:

function func_wp_vue(){
     wp_enqueue_script('wpvue_vuejs');
     wp_enqueue_script('wpvue_vuejs1'); // <- no longer needed

     $str= "<div id='app'>"
           ."Message from Vue: "
           ."</div>";
     return $str;
 }
Enter fullscreen mode Exit fullscreen mode
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

Collapse
 
dgmann profile image
DGMANN

Thank you Jony! :)
That are two really good points! I added it to the article.