Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Vite work with Vue 2 #305

Closed
naknode opened this issue May 29, 2020 · 33 comments
Closed

Make Vite work with Vue 2 #305

naknode opened this issue May 29, 2020 · 33 comments
Labels
enhancement New feature or request

Comments

@naknode
Copy link

naknode commented May 29, 2020

Do NOT ignore this template or your issue will have a very high chance to be closed without comment.

Describe the bug

Trying Vite on a fresh vue 2.5 / typescript app.

Reproduction

  • Create a new app: npm init vite-app vue25 --template vue

  • Replace package.json with this:

{
  "name": "vue25",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "vue": "~2.6.10"
  },
  "devDependencies": {
    "vite": "^0.17.0",
    "vue-template-compiler": "^2.6.11"
  }
}

System Info

  • required vite version: 0.18.0
  • required Operating System: macOS Catalina 10.15.4
  • required Node version: 10.16.0
  • Optional:
    • npm/yarn version: 6.14.4
    • Installed vue version (from yarn.lock or package-lock.json)
    • Installed @vue/compiler-sfc version

I thought this worked with Vue 2.5 as @vue/compiler-sfc is vue 3... only.

@m4rvr
Copy link
Contributor

m4rvr commented May 29, 2020

It doesn't work with Vue 2 and vue-template-compiler isn't the right package. So the error is correct. Use Vue 3 and it will work.

@yyx990803
Copy link
Member

Unfortunately Vite doesn't work with Vue 2 (at least for now). We should make it work though.

@yyx990803 yyx990803 added enhancement New feature or request and removed pending triage labels May 29, 2020
@yyx990803 yyx990803 changed the title Error: a local installation of vue is detected but no matching @vue/compiler-sfc is found. Make sure to install both and use the same version. Make Vite work with Vue 2 May 29, 2020
@naknode
Copy link
Author

naknode commented May 29, 2020

I appreciate the response. Thanks for the hard work Evan, Marvin and company.

@m4rvr
Copy link
Contributor

m4rvr commented May 29, 2020

I didn't do anything, Evan is here the brain. 😄

@jfoliveira
Copy link

jfoliveira commented May 30, 2020

Could you point us to any doc/blog post/tutorial/guide/a one line npx command/... on how to init a Vite+Vue3+TypeScript web front-end app?
Everything I found on my google searches mix too many other concepts together, making it hard to focus on Vite+Vue3+TS.

Update 1:
Based on the README Getting started I tried the following help commands to see the init options, but no luck:

$ npm init vite-app --help
No results for "init" "vite-app"
$ npx vitejs/vite --help
Cannot find module '../dist/cli'
Require stack:
- ~/.npm/_npx/59851/lib/node_modules/vite/bin/vite.js

Update 2:
Based on the README TypeScript section

Vite supports importing .ts files and <script lang="ts"> in Vue SFCs out of the box.

So nothing has to be done?
Do I need to add typescript to my project dependencies?
Should I use vue-cli instead of vite-app?

@m4rvr
Copy link
Contributor

m4rvr commented May 30, 2020

@jfoliveira Normally you have typescript listed in devDependencies in a TypeScript project but I think it also works without it. Vite already installs it but yes - it works without installing additional dependencies. Just use lang="ts" in your <script> and .ts instead of .js.

@jfoliveira
Copy link

jfoliveira commented May 31, 2020

@MarvinRudolph Yeah, but I couldn't find typescript listed in package-lock.json under vite or @vue/compiler-sfc or rollup* so that's why I was curious how the magic was working.

Anyway, tried your suggestion and here is what I did, achieving partial success:

// created a new app:
npm init vite-app my-vue3-vite-ts

// app created
// renamed main.js to main.ts
// changed index.html script tag to:

  <script lang="ts" type="module" src="/src/main.ts"></script>

In the HellowWorld.vue file created by vite I defined a type SomeType and a function using it I also added <script lang="ts"> after the </template> closing tag and wrote some TypeScript specific code:

...
</template>
<script lang="ts">
export interface SomeType {
  someProp: string
}

function tsLogValue(param1: SomeType): void {
  console.log('Param value strongly typed with TS: ', param1.someProp);
}

tsLogValue(123); // vite/tsc should fail to compile this?!?
tsLogValue({ someProp: 'prop value'}); // this should compile fine
...
export default {

Questions:

  1. How to setup vite so it fails to reload/build a component/file when there is a TS syntax error like the one showed above in tsLogValue(123)?

  2. Is there anyway to tell npm init vite-app something like:

hey, vite - you new best friend of people like me that doesn't want or doesn't care to understand the internals of bundling tools - I already know I wanna use TypeScript in this project, would you please name the files with .ts extension and adjust the <script> tags accordingly? Thanks buddy!

That would be helpful!

@m4rvr
Copy link
Contributor

m4rvr commented May 31, 2020

@jfoliveira vite doesn’t do type-checking like in the readme explained. You need to use tsc for that (with —noEmit or —emitDeclarationOnly). Just set it up as a separate script in your package.json.

@jfoliveira
Copy link

jfoliveira commented May 31, 2020

Oohh, I missed that part, sorry.

Now I followed the steps in the README. Created a tsconfig.json file in the root of the project, so I can be warned by TS features not supported by esbuild:

{
    "compilerOptions": {
        "isolatedModules": true
    }
}

Changed my package.json (looks correct?) to use tsc in both build and dev mode:

  "scripts": {
    "dev": "tsc --noEmit && vite",
    "build": "tsc --noEmit && vite build"
  },

So I should no longer run npx vite but actually serve my app in dev mode with npm run dev, right?

npm run dev
sh: tsc: command not found

Hmmmm, now I think I got it. Vite uses esbuild which supports some TypeScript, but not full TypeScript. If one wants to go full TypeScript then TypeScript needs to be added to the vite created project. Right?

Let's try:
Add TypeScript dependency:

npm i -D typescript

Attempted to serve the app in dev mode with vite again, but didn't work. Notice the errors come mainly from node_modules/@vue/* packages. Am I missing something again?

$ npm run dev

> my-vue3-vite-ts@0.0.0 dev ~/my-vue3-vite-ts
> tsc --noEmit && vite

node_modules/@vue/reactivity/dist/reactivity.d.ts:166:13 - error TS2339: Property 'matchAll' does not exist on type 'SymbolConstructor'.

166     [Symbol.matchAll]: infer V;
                ~~~~~~~~

node_modules/@vue/reactivity/dist/reactivity.d.ts:168:13 - error TS2339: Property 'matchAll' does not exist on type 'SymbolConstructor'.

168     [Symbol.matchAll]: V;
                ~~~~~~~~

node_modules/@vue/runtime-core/dist/runtime-core.d.ts:437:20 - error TS2344: Type 'Function & T[key]["get"]' does not satisfy the constraint '(...args: any) => any'.
  Type 'Function' provides no match for the signature '(...args: any): any'.

437     } ? ReturnType<T[key]['get']> : ReturnType<T[key]>;
                       ~~~~~~~~~~~~~

node_modules/@vue/runtime-core/dist/runtime-core.d.ts:437:48 - error TS2344: Type 'T[key]' does not satisfy the constraint '(...args: any) => any'.
  Type 'T[keyof T]' is not assignable to type '(...args: any) => any'.
    Type 'T[string] | T[number] | T[symbol]' is not assignable to type '(...args: any) => any'.
      Type 'T[string]' is not assignable to type '(...args: any) => any'.

437     } ? ReturnType<T[key]['get']> : ReturnType<T[key]>;
                                                   ~~~~~~

node_modules/@vue/runtime-core/dist/runtime-core.d.ts:950:10 - error TS2748: Cannot access ambient const enums when the '--isolatedModules' flag is provided.

950 export { TrackOpTypes }
             ~~~~~~~~~~~~

node_modules/@vue/runtime-core/dist/runtime-core.d.ts:976:10 - error TS2748: Cannot access ambient const enums when the '--isolatedModules' flag is provided.

976 export { TriggerOpTypes }
             ~~~~~~~~~~~~~~

src/main.ts:2:17 - error TS2307: Cannot find module './App.vue' or its corresponding type declarations.

2 import App from './App.vue'
                  ~~~~~~~~~~~


Found 7 errors.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-vue3-vite-ts@0.0.0 dev: `tsc --noEmit && vite`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the my-vue3-vite-ts@0.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     ~/.npm/_logs/2020-05-31T15_05_17_994Z-debug.log

@mdbetancourt
Copy link

bring support to vue 2 is a totally waste of time, better wait for vue 3 stable version dude

@naknode
Copy link
Author

naknode commented Jun 4, 2020

@mdbetancourt Not every Vue project started recently. You have enterprise applications as well countless others who can't upgrade right now. Get some perspective :\

@mdbetancourt
Copy link

@naknode exactly and this is an experimental project... and afaik they are doing everything they can to make vue 3 backward compatible with vue 2 so before try using an experimental lib and migrate to it you should first try migrate to vue 3, so instead of spending time doing this compatible with vue 2 that time could be used to develop more features.
Also this kind of things give more life to vue 2 so people will be more reluctant to migrate.

@cdll
Copy link

cdll commented Jun 24, 2020

i 've ever imagined that might vite support plugin to pluggablly support vue@2.

@underfin
Copy link
Member

underfin commented Jul 20, 2020

Hey guys, I write a plugin to suppot vue2.It can worked fine in dev.See https://github.com/underfin/vite-plugin-vue2

@niveKKumar
Copy link

niveKKumar commented Aug 26, 2020

Hey guys, I write a plugin to suppot vue2.It can worked fine in dev.See https://github.com/underfin/vite-plugin-vue2

Hey I am new to Vue/Vite, so the best way for me learning vue is through vue 2 and the new composition api (cause there are much more rescources). I first tried Vue 3, where I loved Vite. Could you explain me how to integrate Vue 2 with Vite (the fast build is incredible), I couldn't really figure out how to use it in my Vue 2 project.I don't need Typescript support. Kind regards

@jqhr
Copy link

jqhr commented Sep 29, 2020

@yyx990803 ,I think you should not spend a lot of time to make vite compatible with vue2, vue3 is great and for future.and users of vue2 will switch to vue3.
I am writing a repo to support vue2, and maintain it until most users of vue2 switching to vue3.
I waited for vue3 for a long time.the time of vue3 developing was compatible with vue3.This was a pity.
https://gitee.com/tserve/tserve.git. I put it on gitee, If this project is stable for production environment, I will put it on github.
Thanks

@Djaler
Copy link

Djaler commented Jan 2, 2021

Hey guys, I write a plugin to suppot vue2.It can worked fine in dev.See https://github.com/underfin/vite-plugin-vue2

can you update it for vite 2, please?

@underfin
Copy link
Member

underfin commented Jan 3, 2021

Yeah. I will work for it.

@underfin
Copy link
Member

underfin commented Jan 5, 2021

@Djaler The major feature is already works.I thinkt it shoule be closed.

@underfin underfin closed this as completed Jan 5, 2021
@xialvjun
Copy link

xialvjun commented Jan 5, 2021

@underfin how about adding a create-vite-app --template vue2?

@joalves
Copy link

joalves commented Feb 22, 2021

I don't seem to be able to run it on my macbook pro.

First I get a warning from yarn/npm about @vue/compiler-sfc depending on Vue3:

➜  npm ci
npm WARN ERESOLVE overriding peer dependency
npm WARN Found: vue@2.6.12
npm WARN node_modules/vue
npm WARN   vue@"^2.6.12" from the root project
npm WARN   3 more (@sentry/vue, vite-plugin-vue2, vuetify)
npm WARN
npm WARN Could not resolve dependency:
npm WARN peer vue@"3.0.5" from @vue/compiler-sfc@3.0.5
npm WARN node_modules/@vue/compiler-sfc
npm WARN   @vue/compiler-sfc@"^3.0.0-rc.5" from vite-plugin-vue2@1.2.1
npm WARN   node_modules/vite-plugin-vue2

If I run the app everything seems to be fine. It prints vite's message on the console:

yarn dev

yarn run v1.22.0
$ vite

 ⚡ Vite dev server running at:

  > Local:    http://localhost:3000/
  > Network:  http://192.168.1.104:3000/

  ready in 820ms.

But then any request to the app just returns a 404:

HTTP/1.1 404 Not Found
Access-Control-Allow-Origin: *
Date: Mon, 22 Feb 2021 16:24:40 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 0

What am I doing wrong?

Here is my vite config:

import { createVuePlugin } from 'vite-plugin-vue2';

export const plugins = [
  createVuePlugin(/*options*/)
];

// https://vitejs.dev/config/
export default {
  plugins,
  server: {
		proxy: {
			"/auth": {
				target: "http://localhost:8000",
				ws: true,
				changeOrigin: true,
			},
			"/v1": {
				target: "http://localhost:8000",
				ws: true,
				changeOrigin: true,
			},
		},
		disableHostCheck: false,
		https: false,
    open: true,
  }
}

And my main.js:

import "@babel/polyfill";
import Vue from "vue";
import vuetify from "./plugins/vuetify";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import * as Sentry from "@sentry/vue";
import { Integrations } from "@sentry/tracing";

Vue.config.productionTip = false;
Sentry.init({});

new Vue({
	router,
	store,
	vuetify,
	render: (h) => h(App),
}).$mount("#app");

@martinussuherman
Copy link

@joalves I've made template for Vue2 + TS + Vite, you can see it here. Hope that helps.
@xialvjun, I agree, that would be nice.

Regards,

Martinus

@lstoeferle
Copy link

lstoeferle commented Feb 25, 2021

I also created a vite vue2 composition-api example project very recently without any vue cli dependencies: here.

@joalves
Copy link

joalves commented Feb 25, 2021

Thanks, both! I'll check it out.

@joalves
Copy link

joalves commented Feb 28, 2021

With those examples I was able to port my vuetify app to vite. But doesn't seem to be anything like vuetify-loader for vite. I have to manually load all the vuetify components, making all the views look like this:

  import { mapGetters } from "vuex";
  import {
    VApp, VAppBar, VMain, VAppBarNavIcon, VToolbarTitle, VRow, VCol, VTextField, VIcon, VBtn, VNavigationDrawer, VList,
    VDivider, VListItem, VListItemAction, VListItemContent, VListItemTitle,
  } from 'vuetify/lib'

 export default {
    components: {
      VApp, VAppBar, VMain, VAppBarNavIcon, VToolbarTitle, VRow, VCol, VTextField, VIcon, VBtn, VNavigationDrawer, VList,
      VDivider, VListItem, VListItemAction, VListItemContent, VListItemTitle,
    },
    ...

Is there any other solution that I might not have seen?

Thanks

@Djaler
Copy link

Djaler commented Feb 28, 2021

@joalves you can try https://github.com/vatson/rollup-plugin-vuetify

@joalves
Copy link

joalves commented Mar 8, 2021

Thank you @Djaler!
But I was not able to configure it with vite. Do you have a working example?

@Djaler
Copy link

Djaler commented Mar 8, 2021

No, I just used it one time with rollup

@kongondo
Copy link

kongondo commented Mar 14, 2021

With those examples I was able to port my vuetify app to vite. But doesn't seem to be anything like vuetify-loader for vite. I have to manually load all the vuetify components, making all the views look like this:

  import { mapGetters } from "vuex";
  import {
    VApp, VAppBar, VMain, VAppBarNavIcon, VToolbarTitle, VRow, VCol, VTextField, VIcon, VBtn, VNavigationDrawer, VList,
    VDivider, VListItem, VListItemAction, VListItemContent, VListItemTitle,
  } from 'vuetify/lib'

 export default {
    components: {
      VApp, VAppBar, VMain, VAppBarNavIcon, VToolbarTitle, VRow, VCol, VTextField, VIcon, VBtn, VNavigationDrawer, VList,
      VDivider, VListItem, VListItemAction, VListItemContent, VListItemTitle,
    },
    ...

Is there any other solution that I might not have seen?

Thanks

I am using vite-plugin-components with a custom resolver for Vuetify as described in the section Importing from UI Libraries. I have a simple conditional check (in my case no other components would meet the condition except for Vuetify components) like this:

ViteComponents({
 customComponentResolvers: [
   (name) => {
    // where `name` is always CapitalCase
    if (name.startsWith("V"))
     return { importName: name, path: "vuetify/lib" };
    },
  ],
})

With the above, I neither have to import Vuetify Components in my .vue files nor add them to components property.

@mactanxin
Copy link

With those examples I was able to port my vuetify app to vite. But doesn't seem to be anything like vuetify-loader for vite. I have to manually load all the vuetify components, making all the views look like this:

  import { mapGetters } from "vuex";
  import {
    VApp, VAppBar, VMain, VAppBarNavIcon, VToolbarTitle, VRow, VCol, VTextField, VIcon, VBtn, VNavigationDrawer, VList,
    VDivider, VListItem, VListItemAction, VListItemContent, VListItemTitle,
  } from 'vuetify/lib'

 export default {
    components: {
      VApp, VAppBar, VMain, VAppBarNavIcon, VToolbarTitle, VRow, VCol, VTextField, VIcon, VBtn, VNavigationDrawer, VList,
      VDivider, VListItem, VListItemAction, VListItemContent, VListItemTitle,
    },
    ...

Is there any other solution that I might not have seen?
Thanks

I am using vite-plugin-components with a custom resolver for Vuetify as described in the section Importing from UI Libraries. I have a simple conditional check (in my case no other components would meet the condition except for Vuetify components) like this:

ViteComponents({
 customComponentResolvers: [
   (name) => {
    // where `name` is always CapitalCase
    if (name.startsWith("V"))
     return { importName: name, path: "vuetify/lib" };
    },
  ],
})

With the above, I neither have to import Vuetify Components in my .vue files nor add them to components property.

Hi I'm new to vite.
After followed your steps I was able to have Vuetify Components imported but no CSS 🤔
the component syntax like <v-btn> part works find, however even if I add color='primary' to my code, it's always showing a grey button, the same as v-card
Is there anything like extra css steps I need or extra settings?
Thanks

@kongondo
Copy link

kongondo commented Mar 15, 2021

@mactanxin

I hope we are not getting off-topic here :-).

My setup is similar to @lstoeferle's here, minus the TS, WindiCSS, etc.

In src/main.js

import Vue from 'vue'
import App from '@/App.vue'
import { createApp, h } from 'vue-demi'
import vuetify from './plugins/vuetify'
// ....

Vue.config.productionTip = false
Vue.config.devtools = true

const app = createApp({
vuetify,
render: () => h(App),
})

app.mount('#app')

In src/plugins/vuetify.js

import Vue from 'vue'
import Vuetify from 'vuetify/lib/framework'

Vue.use(Vuetify)

export default new Vuetify({...vuetify options if you wish}})

In a component (.vue)

<v-btn depressed color="primary" @click="handleButtonClick()">
My Primary Button
</v-btn>

This works. Vuetify colors and classes work. The only thing that currently doesn't work is v-icon but I suspect I am missing some configuration.

However, I think I will be changing my setup to use rollup-plugin-vuetify instead since it supports both auto-importing of Vuetify components and Vuetify tree-shaking.

Hope this helps.

@mactanxin
Copy link

mactanxin commented Mar 16, 2021

@mactanxin

I hope we are not getting off-topic here :-).

My setup is similar to @lstoeferle's here, minus the TS, WindiCSS, etc.

In src/main.js

import Vue from 'vue'
import App from '@/App.vue'
import { createApp, h } from 'vue-demi'
import vuetify from './plugins/vuetify'
// ....

Vue.config.productionTip = false
Vue.config.devtools = true

const app = createApp({
vuetify,
render: () => h(App),
})

app.mount('#app')

In src/plugins/vuetify.js

import Vue from 'vue'
import Vuetify from 'vuetify/lib/framework'

Vue.use(Vuetify)

export default new Vuetify({...vuetify options if you wish}})

In a component (.vue)

<v-btn depressed color="primary" @click="handleButtonClick()">
My Primary Button
</v-btn>

This works. Vuetify colors and classes work. The only thing that currently doesn't work is v-icon but I suspect I am missing some configuration.

However, I think I will be changing my setup to use rollup-plugin-vuetify instead since it supports both auto-importing of Vuetify components and Vuetify tree-shaking.

Hope this helps.

Thank you so much, everything works fine. 😎

@jost-s
Copy link

jost-s commented Mar 28, 2021

The vite-plugin-component support Vuetify out of the box as well now.

import { defineConfig } from 'vite';
import { createVuePlugin } from 'vite-plugin-vue2';
import ViteComponents, { VuetifyResolver } from 'vite-plugin-components';

export default defineConfig({
  plugins: [
    createVuePlugin(),
    ViteComponents({
      customComponentResolvers: [VuetifyResolver()]
    })
  ]
});

@github-actions github-actions bot locked and limited conversation to collaborators Jul 16, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests