Export Vue and Vuex in a custom npm package
P粉014218124
P粉014218124 2024-03-27 20:02:39
0
1
319

I'm trying to break out a Vue/Vuex project into privately hosted npm packages. I think I'm getting there, but I'm not sure of my current layout, so far I've:

src/
├── BrokerProposal
│   ├── FormInputs
│   ├── index.js
│   └── modals
└── store
    ├── index.js
    └── modules
        └── proposal
            ├── actions
            ├── getters
            ├── helpers
            ├── mutations
            └── states
                └── validations

My goal is to make the BrokerProposal directory importable, which is accomplished with the first index.js file:

const BrokerProposal = require('./BrokerCalculator.vue');

function install(Vue) {
    if (install.installed) return;
    install.installed = true;
    Vue.component("v-broker-proposal", BrokerProposal);
  }
  
const plugin = {
    install
};

let GlobalVue = null;
if (typeof window !== "undefined") {
    GlobalVue = window.Vue;
} else if (typeof global !== "undefined") {
    GlobalVue = global.vue;
}
if (GlobalVue) {
    GlobalVue.use(plugin);
}

BrokerProposal.install = install;

export default BrokerProposal;

This project also uses vuex, so I broke out the mutators etc. of the state into this package to be used with the BrokerProposal, the end user can bind this storage after importing, here is the index.js file:

import Vue from 'vue'
import Vuex from 'vuex'

// Vuex Modules
import tabs from './modules/tabs'
import proposal from './modules/proposal'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    tabs,
    proposal,
  },
})

export default store

I feel like I should include another index.js file at the same level as /src since there is a "main" section in the package.json file that must point to something?

P粉014218124
P粉014218124

reply all(1)
P粉463840170

Side effects such as Vue.use(Vuex) and GlobalVue.use(plugin) should be avoided as they may interfere with projects using this package. It is the project's responsibility to set up the plugin with the appropriate Vue instance.

All public exports can be named exports at the entry point, for example src/index.js:

export { default as BrokerProposal } from './BrokerProposal';
export { default as store } from './store';

It is also a good practice to export components in case you need to import them locally, rather than relying on Vue.component for global registration.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template