Using vue-cli to build Wordpress plugin including HMR

R.D.
2 min readApr 6, 2019

--

This is an opinionated workflow to build Wordpress plugin with VueJS (vue-cli 3). Most often I using this boilerplate generator to quickly generate empty object-oriented Wordpress plugin. I couldn’t find the proper workflow to build Wordpress plugin with vue-cli including HMR, so here's mine.

Inside plugin directory run:

vue create vue 

Now you have vue folder inside plugin directory. Create file vue.config.js

module.exports = {
productionSourceMap: false,
publicPath: process.env.NODE_ENV === 'production'
? '/wp-content/plugins/plugin_name/dist/'
: 'http://localhost:8080/',
outputDir: '../dist',
configureWebpack: {
devServer: {
contentBase: '/wp-content/plugins/plugin_name/dist/',
allowedHosts: ['your-local-wp-host.test'],
headers: {
'Access-Control-Allow-Origin': '*'
},
},
externals: {
jquery: 'jQuery'
},
output: {
filename: 'js/[name].js',
chunkFilename: 'js/[name].js',
},
},
css: {
extract: {
filename: 'css/[name].css',
chunkFilename: 'css/[name].css'
}
},
};

Change plugin_name and your-local-wp-host.test to match your case.

Open main.js inside vue and change initialization of VueJS like this:

document.addEventListener('DOMContentLoaded', () => {
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');
});

Somewhere inside Wordpress template must be an element with ID app. You can check if this element exists before creating Vue instance.

Now open Wordpress plugin where you enqueue scripts and styles. You need function/method to check if http://localhost:8080 is resolving:

private function is_develop_serve()
{
$connection = @fsockopen('localhost', '8080');

if ( $connection ) {
return true;
}

return false;
}

And use it

public function enqueue_scripts() {

if ( $this->is_develop_serve() ) {
wp_enqueue_script( $this->plugin_name . '_dev', 'http://localhost:8080/js/app.js', [], $this->version, false );
} else {
wp_enqueue_script( $this->plugin_name . '_chunks', plugin_dir_url( __DIR__ ) . 'dist/js/chunk-vendors.js', [], $this->version, false );
wp_enqueue_script( $this->plugin_name, plugin_dir_url( __DIR__ ) . 'dist/js/app.js', [], $this->version, false );
}

}
public function enqueue_styles() {

if ( $this->is_develop_serve() ) {
wp_enqueue_style( $this->plugin_name . '_dev', 'http://localhost:8080/css/app.css', [], $this->version, 'all' );
} else {
wp_enqueue_style( $this->plugin_name, plugin_dir_url( __DIR__ ) . 'dist/css/app.css', [], $this->version, 'all' );
}

}

If you don’t use earlier mentioned plugin boilerplate generator you will need modify these methods accordingly.

Basically, this is it. Inside plugin vue folder run yarn serve and you will be able to access your app by navigating to http://localhost:8080 or http://yourproject.test, every time you change something watcher will trigger update without page reload (you will see [HMR] Waiting for update signal from WDS…) if HMR is working properly.

--

--