【发布时间】:2021-05-27 07:00:32
【问题描述】:
我在尝试在 lib 和应用程序之间拆分代码时遇到问题。 我想使用 Vuejs + TypeScript + WebPack,这似乎是一个很好的组合。 我在尝试从库中调用应用程序时遇到了一些问题。这似乎与 d.ts 文件有关。
// powershell output
13:22 Could not find a declaration file for module 'my-lib'. 'path/my-lib.common.js' implicitly has an 'any' type.
Try `npm install @types/my-lib` if it exists or add a new declaration (.d.ts) file containing `declare module 'my-lib';`
11 | // import HelloWorld from "./components/HelloWorld.vue";
12 |
> 13 | import sayHello from "my-lib";
| ^
14 |
15 | export default Vue.extend({
16 | name: "App",
我不想通过设置strict=true 来绕过问题。我想在我的库中正确导出我的符号。
我的测试场景很简单:
- lib 导出 sayHello 方法
// helloworld.ts
export function sayHello() {
console.log('hi')
}
// index.ts
export {sayHello} from './helloworld';
- 应用调用 sayHello 方法
// App.vue
<template>
<div id="app">
<button v-on:click="showMsg">Click Me</button>
</div>
</template>
<script lang="ts">
import Vue from "vue";
import sayHello from "my-lib";
export default Vue.extend({
name: "App",
components: {},
methods: {
showMsg: function() {
sayHello();
}
}
});
</script>
(如果我通过直接调用 console.log 来替换 sayHello,应用程序可以正常工作)
我使用vue create 来生成这两个项目。
在 lib 端,我设置了以下配置:
// package.json
"name": "my-lib",
...
"private": true,
"main": "dist/my-lib.common.js",
"scripts": {
...
"build-lib": "vue-cli-service build --target lib src/index.ts",
...
// tsconfig.json
...
"declaration": true,
"noImplicitAny": true,
"outDir": "./dist",
...
在应用程序端,我已经使用npm install "../my-lib" 在本地安装了应用程序(路径没问题)。
我了解到,在开发版本中,这是一个不错的选择。
我猜问题出在 d.ts 文件生成的某个地方。我认为 tsc 应该自动创建它们,因为我正在编写打字稿文件。 但我找不到他们。我没有任何 d.ts 文件。
我尝试了多种方法,例如:
- 手动调用
tsc -p tscconfig.json(出现了一些d.ts,但是没有lib,对vue文件不了解,需要用我的build-lib脚本) - 添加
vue.config.js(完全没有变化)
module.exports = {
configureWebpack: {
output: {
libraryExport: "default"
}
}
};
- 更改名称/检查名称/等等。
- 找到old but unanswered message
我是一种Web 开发新手(我是一位经验丰富的软件开发人员)。我正试图把头放在这些技术上。我有一种强烈的感觉,我错过了这个 TypeScript 的东西。当涉及到库中的符号暴露时,我可能会有一些 C++ 反应。我不知道。
我可以提供更多信息、更多代码部分等。我不想太具有侵略性:)
提前谢谢大家!
【问题讨论】:
标签: typescript vue.js webpack .d.ts