我正在开发一个用Typescript和VueJS编写的库。我也在使用webpack来做建筑部分。
我在生成TypeScript声明文件(.d.ts)时遇到了一个问题。
首先,让我们谈谈我的源代码。我有Typescript文件(很明显)和Vue组件。每个Vue组件由两个文件组成:一个.vue文件和一个.ts文件。
让我们举个例子。
我有以下代码:
// index.ts
export { default } from './components/Foobar.vue';
// components/Foobar.vue
<template><p>Hello!</p></template>
<script lang="ts" src="./Foobar.ts"></script>
// components/Foobar.ts
@Component
export default class Foobar extends Vue {
}
构建的输出将如下所示:
lib/
dist/
index.js // my lib
index.d.ts // aggregated .d.ts with dts-bundle
lib/ // all my .d.ts are here !
index.d.ts
components/
Foobar.d.ts
问题是dts-bundle无法输出dist/index.d.ts,因为生成的声明(dist/lib/**/*.d.ts
)无效。它们是由ts-loader生成的。
如果我们查看dist/lib/index.d.ts,我们会发现:
// dist/lib/index.d.ts
export { default } from './components/Foobar.vue'
当然,问题是:/dist/lib/components/Foobar.vue
并不存在。此组件的定义是Foobar.d.ts
,而不是Foobar.vue.d.ts
。
当将每个声明捆绑在一起时,dts-bundle会失败,因为它找不到/dist/lib/components/Foobar.vue.d.ts
。
我怎么才能修复它?
我只需要换掉这个
// dist/lib/index.d.ts
export { default } from './components/Foobar.vue'
通过这个
// dist/lib/index.d.ts
export { default } from './components/Foobar'
我认为这是一个非常常见的错误,我只是在我的webpack配置上做了一些错误。这是我的webpack配置:
{
mode: 'development',
devtool: 'cheap-module-eval-source-map',
entry: 'path/to/index.ts',
output: { /* ... */}
resolve: {
symlinks: true,
extensions: [
'.ts',
'.vue',
'.js',
'.json',
],
modules: [
'node_modules',
]
},
module: {
noParse: /^(vue|vuex)$/,
rules: [
{
test: /\.vue$/,
use: [
{
loader: 'cache-loader',
options: {
cacheDirectory: // cache path
}
},
{
loader: 'vue-loader',
options: {
cacheDirectory: // cache path
}
},
]
},
{
test: /\.ts$/,
use: [
{
loader: 'cache-loader',
options: {
cacheDirectory: // cache path
}
},
{
loader: 'babel-loader'
},
{
loader: 'ts-loader',
options: {
appendTsSuffixTo: [
/\.vue$/
],
}
}
]
}
// ...
}
plugins: [
new ProgressPlugin(),
new FriendlyErrorsWebpackPlugin({
clearConsole: false
}),
new VueLoaderPlugin(),
new ForkTsCheckerWebpackPlugin({
vue: true,
tslint: 'custom path to my file',
formatter: 'codeframe',
}),
new CopyWebpackPlugin(
[
{
from: 'assets',
to: 'dist',
ignore: [
'.gitkeep',
'.DS_Store'
]
}
]
),
new DtsBundlePlugin({
name: `MyModule`,
main: path.join(LIB_PATH, entry.output.path, 'lib', 'index.d.ts'),
out: path.join(LIB_PATH, entry.output.path, 'index.d.ts'),
verbose,
})
],
}
我正在做一个最小的复制库,我会及时编辑这个问题。
同时,如果我需要提供特定的信息,请让我知道。
谢谢你的帮助。
发布于 2018-06-10 01:01:02
好了,我终于找到它了。
vue-loader
用于将vue单文件拆分成不同的webpack资产。目标是让webpack在vue单文件的每个部分(脚本、样式和模板)上执行不同的加载器。
在我的例子中,我没有使用“真正的”vue单文件,因为typescript部分不在.vue文件中,而是在另一个文件中。然后用<script lang="ts" src="./MyComponent.ts"></script>
引用它。
由于ts-loader和vue-loader的工作方式,这样做会导致声明生成失败。
我所要做的就是使用普通的单文件组件。但由于我需要让ts远离我的.vue (因为typescript中的一个已知错误),我必须显式地导入ts模块,而不是引用ts文件,如下所示:
<script lang="ts">
export { default } from './MyComponent.ts';
</script>
我希望我说得很清楚了。
https://stackoverflow.com/questions/50738608
复制相似问题