【问题标题】:Why are ".vue" Single File Components preferred to separate files in TypeScript?为什么“.vue”单文件组件优先于 TypeScript 中的分隔文件?
【发布时间】:2018-08-17 00:29:16
【问题描述】:

根据documentation我应该在.vue文件中写vue组件。我喜欢在 vscode 中使用 TypeScript,因为它具有很棒的导航、自动完成、自动导入和智能感知功能。类型安全也是一个优点。

当我使用.vue 文件时,我在外部导出中失去了智能感知和tyoe 安全。

使用 katashins vue-template-loader 我可以找回所有这些。

为什么我应该在 TypeScript 中使用 .vue 文件?

Here 是我使用 katashin 的精彩加载器的仓库。

[编辑] 下面是使用 vetur 0.11.0、vscode 1.21.0 和 vue cli 的 HelloWorld.spec.ts 文件的快速显示。

可以看到问题第 11 行。 可以使用any 关键字解决,但会失去类型安全性。

【问题讨论】:

  • 只是为了确认一下:您是否在 TypeScript 中使用了<script> 标签?您是说在这种情况下丢失了自动完成功能,还是将其与纯 JavaScript 进行比较?
  • 我将 HelloWorld.vue 替换为 HelloWorld > index.ts, HelloWorld > style.scss, HelloWorld > template.html
  • 我是说当我在另一个文件中导入一个文件时,我失去了自动完成功能。例如,如果我想测试 HelloWorld.vue,我不会在测试文件中使用 typescript 自动完成功能。
  • 你用的是什么IDE?
  • 我正在使用 vscode!!

标签: typescript vue.js vuejs2 scaffolding separation-of-concerns


【解决方案1】:

在 VSCode 中,安装 Vetur Extension/Plugin 以编辑 .vue 文件。

例如,git clonehttps://github.com/Microsoft/TypeScript-Vue-Starter 项目并转到:

  • 菜单文件 -> 打开文件夹...

  • .vue 文件完美地带有<script lang="ts"> 标签

如下截图所示:

作为项目需要的依赖项,再次检查https://github.com/Microsoft/TypeScript-Vue-Starter。作为参考,以下是它的依赖项:

  "dependencies": {
    "vue": "^2.5.2",
    "vue-class-component": "^6.0.0",
    "vue-property-decorator": "^6.0.0",
    "vue-router": "^3.0.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.1",
    "ts-loader": "^2.0.3",
    "typescript": "^2.3.2",
    "vue-loader": "^12.0.3",
    "vue-template-compiler": "^2.5.2",
    "webpack": "^2.5.0"
  }

还有一个webpack.config.js 摘录(处理.vue 文件的地方):

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this necessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
          }
          // other vue-loader options go here
        }
      },

【讨论】:

  • 非常感谢您的回答。它非常完整,当我尝试它时,我被进一步阻止了。我必须在我的测试中导入.vue 文件。由于 shims.d.ts 的“假打字”导入导致所有道具/数据/方法/动作无法访问。只有所有组件共有的特性是可测试的。但是,使用@ktsn 模板加载器的情况并非如此。 (see other issue)。为什么我还要有.vue 文件?
  • 嗯,自动完成功能适用于除测试以外的所有内容,您的意思是这样]?
  • 我添加了一个我看到的和不喜欢的例子。
  • 我确实在测试中导入了 vue 文件。我还想将它们导入其他 vuejs 组件中。它将帮助我使用依赖注入来编写接口。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
  • 2017-06-19
  • 2021-10-11
  • 2020-01-19
  • 1970-01-01
  • 2017-07-09
  • 2017-08-07
相关资源
最近更新 更多