簡體   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