VueJS and Cordova - file:// Not supported?! A Workaround

May 18, 2017 18:05

VueJS is my frontend Javascript framework of choice. Cordova is my mobile prototyping framework of choice. Today, I wanted to see if I could quickly take a web app I was working on, and make it into a web application super quick.

Everything was awesome until I hit this:

Build complete.

Tip: built files are meant to be served over an HTTP server.
Opening index.html over file:// won't work.

Bugger - Cordova uses file://. As expected, when using the distribution in Cordova, I was met with a blank page 😭

Don't worry - I found the issue, and have a really quick fix!

My current workflow for vue is quite simple.

$ npm install -g vue-cli
$ vue init webpack my-project
$ cd my-project
$ npm install
$ npm run dev

Before I drone on about how this webpack is awesome etc etc - I'll tell you what you need to change to get it working if you are having the same problems.

my-project/main.js

... Code ...

const router = new VueRouter({
  mode: 'hash',
  base: __dirname,
  routes: [
  ]
})

... Code ...

Change the mode of the VueRouter from History to Hash.

my-project/config/index.js

... Code ...

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',
    productionSourceMap: true,
   
... Code ...

Change the assetsPublicPath from '/' to './'

I hope my couple of hours of fustration, debugging and code following will be useful for you!