在一個自訂 npm 套件中匯出 Vue 和 Vuex
P粉014218124
P粉014218124 2024-03-27 20:02:39
0
1
285

我正在嘗試將 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,所以我將狀態的變異器等分解到這個包中以與BrokerProposal一起使用,最終用戶可以在導入後綁定這個存儲,這是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」部分必須指向某些內容?

P粉014218124
P粉014218124

全部回覆(1)
P粉463840170

應避免 Vue.use(Vuex)GlobalVue.use(plugin) 等副作用,因為它們可能會幹擾使用此套件的項目。專案有責任使用適當的 Vue 實例設定插件。

所有公共匯出都可以在入口點命名為匯出,例如src/index.js:

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

匯出元件也是一個很好的做法,以防需要在本地導入它們,而不是依賴 Vue.component 進行全域註冊。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!