如何将Vue插件发布至NPM?我的Voca.js Vue插件遇问题求助
Let's break down what's going wrong and fix your plugin step by step. The core issues are misconfigured package entry points, a minor plugin implementation detail, and TypeScript type visibility.
1. Fix Package Entry Points (Critical!)
Looking at your package.json, your main and module fields point to vue-services.*.js, but you built your library with the name vue-voca. That's why your app can't find the plugin code at all—webpack is looking for the wrong files!
Update these fields to match your build output:
{ "main": "dist/vue-voca.umd.js", "module": "dist/vue-voca.common.js" }
2. Improve Plugin Implementation
Using require('voca') in a TypeScript project works, but it's cleaner to use ES imports. Also, ensure we're importing the full Voca library correctly:
Update vue-voca.ts:
import Vue from 'vue'; import voca from 'voca'; export default { install(Vue: typeof Vue) { Vue.prototype.$voca = voca; } };
3. Ensure TypeScript Types Are Recognized
Your type declaration file (vue.d.ts) looks correct, but there are two small tweaks to make sure it's picked up properly:
- Confirm your
types/typingsfield inpackage.jsonpoints to the correct path (your current setting tosrc/vue.d.tsworks because you includedsrc/*in yourfilesarray—if you prefer to ship only built files later, you can enabledeclarationDirintsconfig.jsonto output types todistand update the path). - Keep
declaration: trueintsconfig.json(which you already have) to ensure any additional type files are generated if needed.
4. Optimize Dependencies for Plugin Distribution
Since your plugin is meant to be used with Vue, mark vue as a peer dependency instead of a regular dependency. This prevents duplicate Vue instances in consuming projects and aligns with Vue plugin best practices:
Update package.json dependencies section:
{ "dependencies": { "@types/voca": "^1.4.0", "voca": "^1.4.0" }, "peerDependencies": { "vue": "^2.6.7" } }
5. Test Locally Before Publishing
Before running npm pack, validate your plugin locally using npm link to catch issues early:
- In your plugin project, run
npm link - In your test Vue project, run
npm link vue-voca - Import and activate the plugin in your test project's
main.ts:
import Vue from 'vue'; import { VueVoca } from 'vue-voca'; Vue.use(VueVoca); new Vue({ render: h => h(App) }).$mount('#app');
Now you should be able to use this.$voca.swapCase('Hello World') in your components without the "undefined" error, and TypeScript will provide proper intellisense for $voca.
Final Checks Before Publishing
- Run
npm run buildto confirm yourdistfolder has the correctvue-voca.*files - Verify your
filesarray inpackage.jsonincludes all necessary assets (dist files, source types, etc.) - Ensure
privateis set tofalseso npm allows publishing
内容的提问来源于stack exchange,提问作者HamedFathi

