我用打字本为Voca.js编写了一个非常简单的插件。您可以找到源代码这里。
index.ts
import VueVoca from './vue-voca';
export {
VueVoca
};vue-voa.ts
import vue from 'vue';
export default {
install(Vue: typeof vue) {
Vue.prototype.$voca = require('voca');
}
};vue.d.ts
import Vue from 'vue';
import vc from 'voca';
declare module 'vue/types/vue' {
export interface Vue {
$voca: vc.VocaStatic;
}
}要创建npm包,我使用以下命令
vue-cli-service build --name vue-voca --entry ./src/index.ts --target lib和npm pack.
package.json
{
"name": "vue-voca",
"version": "1.0.0",
"private": false,
"scripts": {
"serve": "vue-cli-service serve ./example/main.ts --open",
"build": "vue-cli-service build --name vue-voca --entry ./src/index.ts --target lib",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@types/voca": "^1.4.0",
"voca": "^1.4.0",
"vue": "^2.6.7"
},
"devDependencies": {
"@vue/cli-plugin-typescript": "^3.4.1",
"@vue/cli-service": "^3.4.1",
"fibers": "^3.1.1",
"sass": "^1.17.2",
"sass-loader": "^7.1.0",
"typescript": "^3.3.3333",
"vue-cli-plugin-component": "^1.10.5",
"vue-template-compiler": "^2.6.7"
},
"files": [
"dist/*.css",
"dist/*.map",
"dist/*.js",
"src/*"
],
"keywords": [
"vue",
"component"
],
"types": "src/vue.d.ts",
"typings": "src/vue.d.ts",
"main": "dist/vue-services.umd.js",
"module": "dist/vue-services.common.js"
}tsconfig
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"declaration": true,
"importHelpers": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}但是在另一个项目中使用npm包后,我得到了一个错误。VueVoca不承认,打字本也不能很好地使用它。




webpack-internal:///./node_modules/vue/dist/vue.runtime.esm.js:620 [Vue warn]: Error in render: "TypeError: Cannot read property 'swapCase' of undefined"
found in
---> <HelloWorld> at src/components/HelloWorld.vue
<App> at src/App.vue
<Root>有人能帮我用正确的npm包写一个正确的插件吗?
发布于 2019-02-27 15:25:50
这里的问题是您已经用TypeScript编写了插件。因此,至少有两个类型定义:
index.ts文件的类型定义现在您的package.json有types/typings字段指向vue.d.ts。对于TypeScript,当导入此库时,它将推断模块增强代码。它永远无法在index.d.ts文件中找到。因此,在Vue组件中,this.$voca()将使用TS,而不是import { VueCoca } from 'vue-coca';
作为解决方案,请将types字段设置为<PATH>/index.d.ts文件。另外,为了简洁起见,将vue.d.ts重命名为augment.d.ts。然后,这个库的调用方应该编写自己的类型文件-- *.d.ts文件,他将导入这个文件,如下所示:
import 'vue-coca/<PATH>/augment.d';或者,您也可以在插件的主index.ts文件中导入这个增强文件。使用这种方法,这个库的用户将不必单独包含它。
https://stackoverflow.com/questions/54908469
复制相似问题