草庐IT

Vite + Vue2 + Vuetify2 + script setup + TypeScript 搭配开发项目

Himekana's 2023-03-28 原文

本文记录如何在 Vue2 环境下尽量使用 Vue3 的 Composition-api 并配合 Vuetify2 使用

前言

之前在改造一个用 Vuetify2 的 项目,由于 Vuetify3 还处于 beta 阶段并且与 Vuetify2 相比缺失一些特性,但又想用 Vue3 的 <script setup> 语法,于是寻找了下相关方案,下面简单记录一下。

开始之前

建议使用 VSCode 开发并安装以下插件且禁用 Vetur:

Vue Language Features (Volar)

TypeScript Vue Plugin (Volar)

初始化

使用 npm init 初始化项目

添加所需依赖

  • vue@2.6.14: 指定 2 版本,不指定的话默认安装 3 版本
  • vue-template-compiler: 将 Vue 2.0 模板预编译为渲染函数
  • vite-plugin-vue2: 让 Vite 支持 Vue2
  • @vue/composition-api: 在 Vue2 项目中使用组合 API
  • unplugin-vue2-script-setup: 在 Vue2 项目中使用 <script setup> 语法糖
  • unplugin-vue-components: 按需自动引入组件
  • @vue/runtime-dom: 配合 Volar

完整依赖如下:

  "dependencies": {
    "@mdi/font": "5.9.55",
    "@vue/composition-api": "^1.6.0",
    "roboto-fontface": "*",
    "vue": "^2.6.14",
    "vuetify": "^2.6.4",
    "webfontloader": "^1.0.0"
  },
  "devDependencies": {
    "@types/node": "^17.0.29",
    "@types/webfontloader": "^1.6.34",
    "@vue/runtime-dom": "^3.2.33",
    "sass": "1.32.12",
    "typescript": "^4.6.3",
    "unplugin-vue-components": "^0.19.3",
    "unplugin-vue2-script-setup": "^0.10.2",
    "vite": "^2.9.5",
    "vite-plugin-vue2": "^2.0.0",
    "vue-template-compiler": "^2.6.14",
    "vue-tsc": "^0.34.10"
  }

文件目录结构

?project
 ┣ ?.vscode
 ┣ ?dist
 ┣ ?node_modules
 ┣ ?src
 ┃ ┣ ?common
 ┃ ┣ ?components
 ┃ ┣ ?plugins
 ┃ ┃ ┣ ?vuetify.ts
 ┃ ┃ ┗ ?webfontloader.ts
 ┃ ┣ ?styles
 ┃ ┣ ?App.vue
 ┃ ┣ ?env.d.ts
 ┃ ┗ ?main.ts
 ┣ ?.gitattributes
 ┣ ?.gitignore
 ┣ ?components.d.ts
 ┣ ?index.html
 ┣ ?package.json
 ┣ ?readme.md
 ┣ ?tsconfig.json
 ┣ ?tsconfig.node.json
 ┣ ?vite.config.ts
 ┗ ?yarn.lock

index.html

来自 Vite 官网

你可能已经注意到,在一个 Vite 项目中,index.html 在项目最外层而不是在 public 文件夹内。这是有意而为之的:在开发期间 Vite 是一个服务器,而 index.html 是该 Vite 项目的入口文件。Vite 将 index.html 视为源码和模块图的一部分。Vite 解析 <script type="module" src="..."> ,这个标签指向你的 JavaScript 源码。甚至内联引入 JavaScript 的 <script type="module"> 和引用 CSS 的 <link href> 也能利用 Vite 特有的功能被解析。另外,index.html 中的 URL 将被自动转换,因此不再需要 %PUBLIC_URL% 占位符了。

<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Vite App</title>
</head>

<body>
  <div id="app"></div>
  <script type="module" src="/src/main.ts"></script>
</body>

</html>

components.d.ts

unplugin-vue-components 自动生成,为自动引入组件提供支持,在 vite.config.ts 中通过以下设置打开

Components({
  dts: true, // enabled by default if `typescript` is installed
})

记得把 components.d.ts 添加到 tsconfig.jsonincludes

tsconfig.json

tsconfig.json 文件中指定了用来编译这个项目的根文件和编译选项。

配置全局类型:

  "compilerOptions": {
    "types": [
      "vite/client",
      "node",
      "vue",
      "vuetify",
      "unplugin-vue2-script-setup/types"
    ],
  },

Volar 需要以下配置来支持 Vue2

  "vueCompilerOptions": {
    "experimentalCompatMode": 2,
    "experimentalTemplateCompilerOptions": {
      "compatConfig": {
        "MODE": 2 // optional
      }
    }
  },

完整配置见 yandere-masonry/tsconfig.json

tsconfig.node.json

配置 vite.config.ts 的 TypeScript 选项

{
  "compilerOptions": {
    "composite": true,
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "types": ["node"]
  },
  "include": ["vite.config.ts"]
}

vite.config.ts

Vite 配置文件,之前安装的插件需要这个文件里配置一下来支持 Vue2、<script setup> 等等

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import { createVuePlugin as Vue2 } from 'vite-plugin-vue2'
import { VuetifyResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import ScriptSetup from 'unplugin-vue2-script-setup/vite'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    // https://github.com/underfin/vite-plugin-vue2
    Vue2({ target: 'esnext' }),
    // https://github.com/antfu/unplugin-vue2-script-setup
    ScriptSetup(),
    // https://github.com/antfu/unplugin-vue-components
    Components({
      // generate `components.d.ts` global declarations
      dts: true,
      // auto import for directives
      directives: true,
      // resolvers for custom components
      resolvers: [
        // Vuetify
        VuetifyResolver(),
      ],
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('src', import.meta.url))
    },
  },
})

src/env.d.ts

提供类型支持:

/// <reference types="vite/client" />

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

declare module 'vuetify/lib/framework' {
  import 'vuetify/types'
  import Vuetify from 'vuetify'
  export default Vuetify
}

src/main.ts

入口文件,在此安装 VueCompositionAPIVuetify

import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api'
import installVuetify from './plugins/vuetify'
import App from './App.vue'

Vue.use(VueCompositionAPI)

const vuetify = installVuetify()
const app = new Vue({
  vuetify,
  render: h => h(App),
})
app.$mount('#app')

src/App.vue

直接使用 <script setup> 语法:

<template>
  <v-app :theme="store.theme">
    <v-app-bar />
    <v-navigation-drawer />
    <v-main app>
      <v-container />
    </v-main>
  </v-app>
</template>

<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup

import { onMounted } from '@vue/composition-api'
import { useVuetify } from './plugins/vuetify'

const vuetify = useVuetify()

onMounted(() => {
  vuetify.theme.dark = true
})
</script>

src/plugins/vuetify.ts

安装 Vuetify,并通过 useVuetify 暴露 $vuetify 实例:

// Styles
import '@mdi/font/css/materialdesignicons.css'
import 'vuetify/dist/vuetify.min.css'

import Vue from 'vue'
import Vuetify from 'vuetify'
import { getCurrentInstance } from '@vue/composition-api'
import { loadFonts } from './webfontloader'

loadFonts()

function installVuetify() {
  Vue.use(Vuetify)
  return new Vuetify({})
}

export default installVuetify

/** Get vuetify instance (For Composition api) */
export function useVuetify() {
  /** Get Instance */
  const instance = getCurrentInstance()
  if (!instance) {
    throw new Error('Should be used in setup().')
  }
  return instance.proxy.$vuetify
}

src/plugins/webfontloader.ts

加载字体:

/**
 * plugins/webfontloader.js
 *
 * webfontloader documentation: https://github.com/typekit/webfontloader
 */

export async function loadFonts() {
  const webFontLoader = await import('webfontloader')

  webFontLoader.load({
    google: {
      families: ['Roboto:100,300,400,500,700,900&display=swap'],
    },
  })
}

效果

启动项目

yarn dev

项目代码见 yandere-masonry

Reference

https://juejin.cn/post/7012240119465771038

https://github.com/logue/vite-vue2-vuetify-ts-starter

https://github.com/antfu/unplugin-vue2-script-setup


Also posted at https://www.nanoka.top/posts/fb7525a/
fin.

有关Vite + Vue2 + Vuetify2 + script setup + TypeScript 搭配开发项目的更多相关文章

  1. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  2. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  3. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  4. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  5. Ruby Sinatra 配置用于生产和开发 - 2

    我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm

  6. ruby - 是否可以覆盖 gemfile 进行本地开发? - 2

    我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI

  7. ruby - 在 Windows 机器上使用 Ruby 进行开发是否会适得其反? - 2

    这似乎非常适得其反,因为太多的gem会在window上破裂。我一直在处理很多mysql和ruby​​-mysqlgem问题(gem本身发生段错误,一个名为UnixSocket的类显然在Windows机器上不能正常工作,等等)。我只是在浪费时间吗?我应该转向不同的脚本语言吗? 最佳答案 我在Windows上使用Ruby的经验很少,但是当我开始使用Ruby时,我是在Windows上,我的总体印象是它不是Windows原生系统。因此,在主要使用Windows多年之后,开始使用Ruby促使我切换回原来的系统Unix,这次是Linux。Rub

  8. ruby-on-rails - 在 Rails 开发环境中为 .ogv 文件设置 Mime 类型 - 2

    我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain

  9. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  10. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

随机推荐