繁体   English   中英

TypeScript文件中导入Vue组件

[英]Importing Vue components in TypeScript file

我一直在尝试将 Vue.js 与 TypeScript 一起使用,我遇到了这个 repo

我在这里遇到了从 TypeScript 导入 Vue 单一组件文件时出错的问题。我正在使用 Visual Studio Code。 请参阅下面的错误。

主.ts:

// The Vue build version to load with the 'import' command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import * as Vue from 'vue'
import App from './App'

/* eslint-disable no-new */
new Vue({
    el: '#app',
    template: '<App/>',
    components: { App }
})

VS代码错误:

 1 ERROR • main.ts [ts] Cannot find module './App'. (4 17)

使用 visual studio 代码在 main.ts 中导入 App.vue 的问题

来自亚历克斯·乔弗

如果您的编辑器对 main.js 文件中的 import App from './App' 行大喊大叫关于找不到 App 模块,您可以将vue-shim.d.ts文件添加到您的项目中,其内容如下:

declare module "*.vue" {
  import Vue from 'vue'
  export default Vue
}

和写 :

import App from './App.vue'

代替

import App from './App'

查看vue-class-component 基本上,您必须将appendTsSuffixTo: [/\\.vue$/]添加到ts-loader的选项,并将esModule: truevue-loader的选项。

// webpack.config.js

{ modules: { rules: [
  {
    test: /\.ts$/,
    exclude: /node_modules|vue\/src/,
    loader: "ts-loader",
    options: { appendTsSuffixTo: [/\.vue$/] }
  },
  {
    test: /\.vue$/,
    loader: 'vue-loader',
    options: {
      esModule: true
    }
  }
]}}

我可能错过了别的东西。

使用vue-cli时,修改vue-loader-conf.js如下:

var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'

module.exports = {
  loaders: utils.cssLoaders({

    sourceMap: isProduction
      ? config.build.productionSourceMap
      : config.dev.cssSourceMap,
    extract: isProduction, esModule: true
  }), esModule: true
}

仅供参考,您可以生成 . 通过在 tsconfig 中打开声明生成来为您的组件创建 d.ts 文件。 json,将它们复制到源目录,看看你得到了什么!

即使是vue.d.ts也有这个问题,因为我在同一个文件中有多个声明。 不得不像这样拆分它们:

在 vue 3 中,这是vue.d.ts ,它必须位于 tsconfig.json 中包含的路径中的某处。

// vue.d.ts
declare module '*.vue' {
    import { DefineComponent } from 'vue'
    // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
    const component: DefineComponent<{}, {}, any>
    export default component
}

我还想在我的 vue 实例上设置全局属性,并通过智能感知在任何组件中使用它们。 在我的vue.d.ts文件中加入如下代码后,编辑器在我import.vue文件到typescript时报错,所以只好单独加一个vue-runtime.d.ts文件,不然不行:

// vue-runtime.d.ts
import '@vue/runtime-core'

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        customFunction: (val: number) => string;
    }
}

然后customFunction将在所有组件上注册!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM