Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import vue.esm.js in vuex mutations test in Webpacker

Tags:

I'm using Webpacker with this approach (requiring me to import vue.esm.js). I would like to test my vuex mutations as described in testing vuex docs. It works when I use import Vue from 'vue', but not when I use import Vue from 'vue/dist/vue.esm'. However, if I don't use vue.esm in my store, my Webpacker Vue app breaks.

Here's my store:

// store.js
import Vue from 'vue/dist/vue.esm' // changing this to import from 'vue' works
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
  count: 0
}

// export `mutations` as a named export
export const mutations = {
  increment: state => state.count++
}

export default new Vuex.Store({
  state,
  mutations
})

Here's my test:

import { mutations } from './store'

// destructure assign `mutations`
const { increment } = mutations

describe('mutations', () => {
  it('INCREMENT', () => {
    // mock state
    const state = { count: 0 }
    // apply mutation
    increment(state)
    // assert result
    expect(state.count).toBe(1)
  })
})

The above test outputs:

 FAIL  app/javascript/test/unit/specs/mutations.spec.js
  ● Test suite failed to run

    myproject/node_modules/vue/dist/vue.esm.js:10671
    export default Vue$3;
    ^^^^^^

    SyntaxError: Unexpected token export

What am I doing wrong?

like image 805
sdellis Avatar asked Dec 15 '17 18:12

sdellis


1 Answers

Not sure if you ever resolved this but I ran into the same problem. What worked for me was to use an alias for 'vue'. Same as here: https://github.com/rails/webpacker/blob/master/docs/webpack.md#configuration

// custom.js
const vueFile = process.env.NODE_ENV === 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js';
module.exports = {
  resolve: {
    alias: {
      vue: vueFile,
      vue_resource: 'vue-resource/dist/vue-resource',
    },
  },
};

// environment.js
const { environment } = require('@rails/webpacker');
const customConfig = require('./custom');
const vue = require('./loaders/vue');

environment.config.merge(customConfig);
environment.loaders.append('vue', vue);

module.exports = environment;

Then update the import in my store and app JS (import Vue from 'vue';) and we're sorted!

like image 100
ellerynz Avatar answered Sep 22 '22 12:09

ellerynz