【发布时间】:2022-01-04 14:45:36
【问题描述】:
我正在尝试将 Vue/Vuex 项目分解为私有托管的 npm 包。我想我到了那里,但是我不确定我目前的布局,到目前为止我有:
src/
├── BrokerProposal
│ ├── FormInputs
│ ├── index.js
│ └── modals
└── store
├── index.js
└── modules
└── proposal
├── actions
├── getters
├── helpers
├── mutations
└── states
└── validations
我的目标是使 BrokerProposal 目录可导入,这是通过第一个 index.js 文件完成的:
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;
这个项目也使用了vuex,所以我把state的mutators等分解到这个包中来配合BrokerProposal,最终用户可以在导入后绑定这个store,这里是index.js文件:
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
我觉得我应该在与/src 相同级别包含另一个 index.js 文件,因为 package.json 文件中有一个“main”部分必须指向某些东西?
【问题讨论】:
-
“我觉得我应该将另一个 index.js 文件包含在与 /src 相同的级别” - 是的。您应该避免像
Vue.use(Vuex)和GlobalVue.use(plugin)这样可能会干扰使用此包的项目的副作用 -
@EstusFlask 我唯一的困惑是如何从那个父级 index.js 文件中导出 vue 组件和状态?
-
它们被重新导出为命名导出。您可以在第三方 Vue 库中看到它是如何工作的,尤其是具有多个组件的库。