vueuse / vue-demi Goto Github PK
View Code? Open in Web Editor NEWπ© Creates Universal Library for Vue 2 & 3
License: MIT License
π© Creates Universal Library for Vue 2 & 3
License: MIT License
Hi!
More than an issue is really a question on how to use this package when you have a plugin library more than just using a composition function like in the demo examples.
Motivation: Allow this library to be installable in both vue 2.x
via Vue.use(VueLibrary)
and in vue 3
using app.createApp(App).use(VueLirbary)
instead of having each version in separate branches (main
for 2.x, next
for 3.x)
For vue 2.x my installation file looks something like this.
export function install(Vue) {
if (install.installed && _Vue === Vue) return;
install.installed = true;
_Vue = Vue;
Vue.prototype.$formUtils = utils;
Vue.component('dynamic-form', DynamicForm);
Vue.component('dynamic-input', DynamicInput);
}
export const AsDynamicForms = {
install,
version,
};
// Automatic installation if Vue has been added to the global scope.
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(AsDynamicForms);
}
Meanwhile for For vue 3.x:
export interface DynamicFormsOptions {
autoValidate?: boolean;
form?: FormOptions;
}
export interface DynamicFormsPlugin {
options?: DynamicFormsOptions;
install(app: App): void;
}
export function createDynamicForms(
options?: DynamicFormsOptions,
): DynamicFormsPlugin {
const vdf: DynamicFormsPlugin = {
options,
install(app: App) {
const self = this;
app.component('dynamic-form', DynamicForm);
app.provide(dynamicFormsSymbol, self);
},
};
return vdf;
}
My initial idea was to use vue-demi
somehow in the code above to use Vue as a parameter in the install function instead of app, (maybe isVue3
flag) but not sure this is the right approach.
Any insight will be really appreciated, thanks in advance πββοΈ
Not exactly an issue with the library but hoping you may be able to help.
After installing @vueuse/core
, when VSCode + typescript shows intellisense and automatically adds imports (for example for ref
or computed
), it is now importing from vue-demi rather than from vue. This would make sense if I was developing a tool/library meant to be used with vue2 and vue3, but I am working on a strictly vue3 project and I'd like things to be imported from vue directly.
Any guidance on how I can tell VSCode to prefer vue instead of vue-demi?
Vue2 components is compiled.
I've started to build a library for vue and wanted to make it compatible with vue2 and vue3, so I decided to use VueDemi.
The library I'm building is vue-insta-stories a component library, I've struggled a little bit to make it compatible with both vue 2 & 3, first I've tried to use but didn't manage to get it working. I was using rollup to build it.
So I checked some examples on the vue-demi repo and discovered that everybody was using render and h to build templates, I switched to render function and everything seems to work nice, except that the first guy using it, was using vue2 and had some errors, after some checking I found out that the h function as different behaviours if used in vue2 and vue3 (I've never used render functions before :D)
To fix the issue I made a wrapper to the h function (h-demi.ts) basically the function has the same interface as vue2 createElement, and if you are using vue3 it adapts the arguments to the h function.
The version of h-demi.ts that I've written is pretty simple, it covers only what I used in vue-insta-stories, and is missing a lot of typings.
I was wondering if a more robust version of h-demi would be a "nice to have" feature inside vue-demi or vue/composition-api. That would help a lot of people that want to build a library and make it compatible with both 2 & 3 versions of vue.
That was my first approach to a library, I may also got the whole building process wrong, but I didn't found examples or really good guides, so i mixed up what I've found (if there is an another way of fix the render issues please tell me <3)
Hi :) Trying vue-demi
(as a dependency of vue-global-api
) on latest nuxt3 version, production build fails since there is no import
matcher. (and currently node condition is set to cjs)
Could not resolve import "vue-demi" in ..../node_modules/vue-global-api/onActivated.mjs using exports defined in ..../node_modules/vue-demi/package.json
It can be fixed by adding import
field to package.json: (should be ideally esm build)
"exports": {
".": {
"require": "./lib/index.cjs.js",
++ "import": "./lib/index.cjs.js",
"node": "./lib/index.cjs.js",
"browser": "./lib/index.esm.js"
},
"./*": "./*"
},
.mjs
and .cjs
extensions so that tooling can infer module type.node
condition can be added to niro resolver but since there are also non Node.js SSR environments (like Cloudflare workers) we would need import only supportwe re using @vueuse/core 5.0.3 and the latest update to vue demi, breaks our build(which was fine a few hours ago).
We re not using vue-demi directly, only through vueuse.
error in ./node_modules/vue-demi/lib/index.mjs
Can't reexport the named export 'computed' from non EcmaScript module (only default export is available)
we re seeing a bunch of these, not only "computed"; everything exported from vue-demi causes this issue.
Imports of resolveDirective
, withDirectives
and many other vue@3 modules are not found in vue-demi
when used in vue@2 environments.
import {
defineComponent,
h,
isVue2,
resolveComponent,
resolveDirective,
withDirectives,
vModelDynamic,
vShow,
} from 'vue-demi';
In vue@2 environments this will result in an error like "export 'withDirectives' was not found in 'vue-demi'
.
Any idea on how to handle these cases?
I am trying to use vue-echarts 6.0.0-rc4, which uses vue-demi 0.7.5.
vue-echarts requires installing @vue/composition-api for Vue2 support.
With @vue/composition-api 1.0.0-rc7, I get:
ERROR in ./node_modules/vue-demi/lib/index.esm.js 18:0-488
"export 'markReactive' was not found in '@vue/composition-api'
I have to back all the way down to @vue/composition-api 1.0.0-beta.13 in order to compile with webpack.
'markReactive' appears to have been removed here: vuejs/composition-api@f204daa#diff-c36c909d3a8f19854e27884759d63990fba3d4de54593dd1537d082d76770e38
https://cdn.skypack.dev/-/[email protected]/dist=es2020,mode=imports/optimized/vue-demi.js
export * from "/-/[email protected]/dist=es2020,mode=imports/optimized/vue.js";
import * as vue from "/-/[email protected]/dist=es2020,mode=imports/optimized/vue.js";
export {vue as Vue};
var isVue2 = false;
var isVue3 = true;
Originally posted by sduduzog July 23, 2021
Here's my package.json
{
"name": "vue-supabase",
"version": "1.0.4",
"description": "A small wrapper for integrating supabase to Vuejs",
"main": "index.js",
"engine": {
"node": ">= 1"
},
"scripts": {
"test": "npm run test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/scottrobertson/vue-supabase.git"
},
"keywords": [
"vue",
"custom",
"supabase"
],
"author": "Scott Robertson",
"types": "index.d.ts",
"license": "MIT",
"files": [
"index.js",
"index.d.ts"
],
"bugs": {
"url": "https://github.com/scottrobertson/vue-supabase/issues"
},
"homepage": "https://github.com/scottrobertson/vue-supabase#readme",
"dependencies": {
"@supabase/supabase-js": "^1.4.2",
"vue-demi": "^0.11.2"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^2.0.0 || >=3.0.0"
}
}
And here's my index.js
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const { inject, isVue3 } = require('vue-demi');
const { createClient } = require('@supabase/supabase-js')
const supabaseKey = 'supabase';
function useSupabase(key = null) {
return inject(key !== null ? key : supabaseKey);
}
exports['default'] = {
supabaseKey,
useSupabase,
install: function (app, options) {
const supabase = createClient(options.supabaseUrl, options.supabaseKey, options.supabaseOptions)
app.provide(supabaseKey, supabase);
if (isVue3){
app.config.globalProperties.$supabase = supabase;
} else {
Object.defineProperties(app.prototype, {
$supabase: {
get: function() {
return supabase;
},
},
});
app.supabase = supabase;
}
}
}
module.exports = exports['default'];
This is from a branch of a vue-supabase fork. It works for vite and vue3 but not for Vue2 using @vue/cli to create the project https://github.com/sduduzog/vue-supabase/tree/use-vue-demi
Should Vue3 try to polyfill all VCA specific helpers, such as set
and del
from reactivity, which are missing?
I'm using vue 2 as default and when switching to vue 3 with npx vue-demi-switch 3
getting a selfHook.bind is not a function
error
When using pnpm
(hoist = false) or yarn@berry
webpack build fails as vue-demi
tries to access @vue/composition-api
without listing it as a dependency.
It is the same issue as #9 but for @vue/composition-api
. Why was is removed from peer dependencies?
Hello,
I am building a library that uses @vue/reactivity to have some reactive data (no Vue components).
The library may be used by a Vue project but also React, Angular, whatever ....
Does vue-demi can help for this "support" ?
Today it seems that is it Vue centric (Vue 2 or 3). Can it make sense to support @vue/reactivity to extends the "universal aspect" ?
Shouldn't it be a peer dependency? I think that this is messing with my app after updating @vue/apollo-composable from 4.0 alpha 9 to alpha 10, which adds vue-demi
vuelidate is using vue-demi to help them with their new version support both Vue 2 and Vue 3. They need access to the equivalent of the Plugin. This is a new type in Vue 3 and should have an equivalent in Vue 2.
Is there a way that Vue-demi could provide a common abstraction?
Here is the open in issue on vuelidate
vuelidate/vuelidate#767
Hi,
After the last update for version 0.8, i cannot run build on my app:
RROR Failed to compile with 42 errors7:36:04 PM
error in ./node_modules/@vueuse/core/node_modules/vue-demi/lib/index.esm.mjs
Can't reexport the named export 'computed' from non EcmaScript module (only default export is available)
error in ./node_modules/@vueuse/core/node_modules/vue-demi/lib/index.esm.mjs
Can't reexport the named export 'createApp' from non EcmaScript module (only default export is available)
error in ./node_modules/@vueuse/core/node_modules/vue-demi/lib/index.esm.mjs
Can't reexport the named export 'customRef' from non EcmaScript module (only default export is available)
error in ./node_modules/@vueuse/core/node_modules/vue-demi/lib/index.esm.mjs
Can't reexport the named export 'defineComponent' from non EcmaScript module (only default export is available)
error in ./node_modules/@vueuse/core/node_modules/vue-demi/lib/index.esm.mjs
Can't reexport the named export 'del' from non EcmaScript module (only default export is available)
error in ./node_modules/@vueuse/core/node_modules/vue-demi/lib/index.esm.mjs
Can't reexport the named export 'getCurrentInstance' from non EcmaScript module (only default export is available)
error in ./node_modules/@vueuse/core/node_modules/vue-demi/lib/index.esm.mjs
Can't reexport the named export 'h' from non EcmaScript module (only default export is available)
Hello, I'm struggling to update from 0.4 to 0.5 because I'm only using Vue 3 at https://github.com/posva/vue-use-spring and I get this TS error:
node_modules/vue-demi/lib/index.d.ts:4:31 - error TS2709: Cannot use namespace 'Vue' as a type.
4 declare const install: (vue?: Vue) => void
~~~
Found 1 error.
I tried adding both vue2 and vue 3 like this: https://github.com/antfu/vueuse/blob/master/package.json but inversing them since I'm using Vue 3 inside of the project but it gave me even more errors π
Do you have any idea of what I'm missing?
Hello, I'm working on supporting both Vue2 and Vue3 in Vue InstantSearch.
I used vue-demi inside Vue InstantSearch. After installing Vue InstantSearch in an empty project, it gives me this error:
ERROR Failed to compile with 1 error 17:19:50
This dependency was not found:
* @vue/composition-api in ./node_modules/vue-demi/lib/index.esm.js
To install it, you can run: npm install --save @vue/composition-api
More details:
In the package.json
of Vue InstantSearch,
"dependencies": {
"vue-demi": "^0.9.1",
// ...
},
"peerDependencies": {
"vue": "^2.6.0 || >=3.0.0-rc.0",
"@vue/composition-api": "^1.0.0-beta.1",
// ...
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
},
"devDependencies": {
"vue": "2.5.18",
// ...
}
You can see the pull request here. And I deployed the temporary build of the pull request via CodeSandbox, which is:
https://pkg.csb.dev/algolia/vue-instantsearch/commit/3341e045/vue-instantsearch
Now I put it in an example:
p9ez8.zip
If you run yarn install && yarn serve
it will show the error message above.
In Vue InstantSearch, we do not use @vue/composition-api
, so left it as optional. The error message goes away only when I install it as a dependency inside the example.
Do you have any idea? Thanks!
Hi.
At first, great library and idea!
I have a feature request.
It would be nice to be able to check the version of the Vue because there are still some differences.
Something like this maybe.
import {h, isVue2} from 'vue-demi';
h('div', {
style: {/*...*/},
...(isVue2 ? {on: {click: onClick}} : {onClick}),
})
Hello @antfu ,
I am currently working on a SPA using vue2
+ options-api
. This SPA imports another component library (vue2
+ @vue/composition-api
), which simply exposes a single vue component. The component library also uses @vueuse/core
using vue-demi
.
Here's an example of the exported component of the library (can not share everything since it's an company internal project)
<template>
<div>
<p>FOO: {{ blub }}</p> <!-- will stay false -->
<button @click.stop="click">CLICK ME</button>
</div>
</template>
<script>
import { defineComponent, ref } from "@vue/composition-api"
import { useLocalStorage } from "@vueuse/core"
export default defineComponent({
setup: (props) => {
const foo = ref(false)
const storageLocale = useLocalStorage("some_key", "en-GB", {
listenToStorageChanges: true,
window,
})
return {
foo,
click: () => {
console.log("before click", foo.value)
foo.value = true
console.log("after click", foo.value) // <-- will be true
},
}
},
})
</script>
So basically everything works pretty good. But as soon as I add the useLocalStorage
or any other composable from @vueuse/core
, the template will not re-render as soon as the button was clicked. The ref value itself works, only the template does not update. I did a lot of debugging together with my colleague, and we figured out that the template will update, as soon as we get rid of all vue-demi
based code.
Dependencies of the SPA:
"dependencies": {
"vue": "^2.6.10",
"@company/components": "1.0.0",
"@vue/composition-api": "1.0.0-beta.25"
},
"devDependencies": {
... all other
}
Dependencies of the ComponentLibrary:
"dependencies": {
"@vueuse/core": "4.0.10"
},
"devDependencies": {
"vue": "^2.6.10",
"@vue/composition-api": "1.0.0-beta.25"
... all other
}
Do you know what could be the issue here?
Kind regards,
Lukas
I think the Usage section in the readme should be updated.
With npm7, peerDependencies are being installed automatically, and having it like that, causes issues with installations. At Vuelidate we had this issue, until I actually went in, and copied what I saw from Vueuse. Basically removing the peerDeps altogether :D
I am not sure if that is the right thing to do though :/ Seems to work for Vueuse/core.
is this just like ahook but for vue3.
I think that's pretty coolοΌ
can add some common things in this project in todo list. for example drop-down or counter
Hi @antfu , i really like this project.
But when i run yarn build
in examples/@vue-demi/use-mouse/
folder, it had a problem.
And i found this error in examples/@vue-demi/use-mouse/src/index.ts
.
Have any solution to fix this? Thank you!
Hi @antfu, big thanks for providing Vue Demi.
Since the breaking change introduced in Vue Composition API 1.0.0-beta.22 getCurrentInstance
only works with the following workaround in Vue 3:
const vm = isVue3 ? getCurrentInstance() : getCurrentInstance().proxy
const lazy = vm.attrs.modelModifiers.lazy // will crash with getCurrentInstance().proxy
I'm trying to use @vueuse/core
with @nuxtjs/composition-api
in my Nuxt project.
And I get a error message:
This dependency was not found:
* @vue/composition-api/dist/vue-composition-api.esm.js in ./node_modules/vue-demi/lib/index.mjs
But @vue/composition-api
have been install. Because @vue/composition-api
is also @nuxtjs/composition-api
's dependency.
I have no idea how to fix it.
Here is reproduction link: codesandbox
Have any solution to fix this? Thank you!
Hello,
I'm having trouble using your library to implement some functions in typescript
. Is showing me the message
"Error: [vue-composition-api] must call Vue.use (VueCompositionAPI) before using any function."
I leave below the error output.
I will appreciate your help and your prompt response.!!
import {ref, reactive, UnwrapRef, Ref } from 'vue-demi';
export function fxReactive<T extends object>(obj: T): UnwrapRef<T> {
return reactive(obj);
}
const fx = fxReactive({
data: []
});
console.log(fx.data);
devDependecies
"@vue/composition-api": "^1.0.0-beta.1",
"vue": "^2.6.11"
dependecies
"vue-demi": "latest"
error
C:\Users\c\Desktop\reactivefx\node_modules\@vue\composition-api\dist\vue-composition-api.common.js:43
throw new Error("[vue-composition-api] " + msg);
^
Error: [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function.
at assert (C:\Users\c\Desktop\reactivefx\node_modules\@vue\composition-api\dist\vue-composition-api.common.js:43:15)
at getVueConstructor (C:\Users\c\Desktop\reactivefx\node_modules\@vue\composition-api\dist\vue-composition-api.common.js:83:9)
at observe (C:\Users\c\Desktop\reactivefx\node_modules\@vue\composition-api\dist\vue-composition-api.common.js:470:15)
at Function.reactive (C:\Users\c\Desktop\reactivefx\node_modules\@vue\composition-api\dist\vue-composition-api.common.js:595:20)
at fxReactive (C:\Users\c\Desktop\reactivefx\src\index.ts:6:10)
at Object.<anonymous> (C:\Users\c\Desktop\reactivefx\src\index.ts:9:12)
at Module._compile (internal/modules/cjs/loader.js:1176:30)
at Module.m._compile (C:\Users\c\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:473:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
at Object.require.extensions.<computed> [as .ts] (C:\Users\c\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:476:12)
My use case is to config ignoredElements
only in Vue 2. Currently we may use:
import { Vue, isVue2 } from 'vue-demi'
if (isVue2) {
Vue.config.ignoredElements.push(...)
}
The problem is that when this code is run with Vue 3, Vue
contains all tree-shakable exports which is not ideal.
So shall we add a Vue2
export from vue-demi so that we can use it like:
import { Vue2 } from 'vue-demi'
if (Vue2) {
Vue2.config.ignoredElements.push(...)
}
And in Vue 3 mode we just export undefined
from vue-demi
so it doesn't hurt the bundle size.
VueRouter 3.x not have hook
@antfu Hi, I noticed that this page is not available. How can I help fix it?
https://antfu.me/posts/make-libraries-working-with-vue-2-and-3
yarn@2
is now stricter about checking dependencies. It does not allow package to import dependency that is not in dependencies or peer dependencies. This causes runtime warnings or build errors.
Reproduction:
https://github.com/Demivan/vue-demi-dependencies
vue-demi
branchyarn
yarn build
yarn node bundle.js
(node:68639) [MODULE_NOT_FOUND] Error: vue-demi tried to access vue, but it isn't declared in its dependencies; this makes the require call ambiguous and unsound.
(Use `node --trace-warnings ...` to show where the warning was created)
master
branch uses fixed version of vue-demi
with updated peer dependencies. With it warning is gone.
I have created proposed fix here: #8
Hi, I was trying to use @vueuse/core when I ran into an issue with this package. I'm using npm 7.0.3, node 15.0.1 and my package.json looks like this:
{
"private": true,
"scripts": {
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"production": "mix --production"
},
"devDependencies": {
"@vue/compiler-sfc": "^3.0.2",
"autoprefixer": "^10.0.1",
"axios": "^0.19",
"cross-env": "^7.0",
"laravel-mix": "^6.0.0-beta.11",
"lodash": "^4.17.19",
"postcss-import": "^12.0.1",
"postcss-nested": "^4.2.3",
"postcss-simple-vars": "^5.0.2",
"resolve-url-loader": "^3.1.0",
"sass-resources-loader": "^2.1.1",
"tailwindcss": "^1.9.6",
"tailwindcss-filters": "^3.0.0",
"vue": "^3.0.2",
"vue-loader": "^16.0.0-beta.10",
"vue-router": "^4.0.0-rc.1",
"vuex": "^4.0.0-rc.1",
"@vueuse/core": "^4.0.0-beta.38"
}
}
I'm using Laravel Mix to compile all the assets (I'll be using Laravel as a backend). Everything was going fine until I tried to use any function from the vueuse package.
The console error looked like this:
Going thru the module code I see some lines are overwritten depending of the Vue version and it looks like the module thinks I'm on version 2 of Vue. Manually changing those lines to the 'v3' fixed the issue. I'm not sure this is Laravel Mix fault (webpack wrapper) or not. Let me know how can I help fixing this issue.
Hello @antfu,
unfortunately I can not use vue-demi
in a micro frontend setup, where the container SPA provides the vue instance via window.Vue
. The web components are using vue-demi
but they crash since it tries to install the composition api on a non existing Vue instance.
[vue-composition-api] No vue dependency found. (in getRegisteredVueOrDefault)
is there any workaround to make this default install(Vue)
call optional?
Hi,I found some issues when I implement vue-demi in vitepress,but switching to vue it is ok,such as onMounted,reactivy data lose.Reactivy data lose hard to repo,so here is a onMounted repo
<script setup lang="ts">
import { onMounted } from "vue-demi"; // in vite,cli is ok ,not work in vitepress
// import { onMounted } from "vue"; // ok
onMounted(() => {
console.log("onMounted");
});
</script>
Hello @antfu,
I am facing a strange issue while using v6.0
of the vue-demi
package in my project. I have a global 'store' which can also be accessed outside of the Vue-context (e.g. in main.ts
). The Vue.use(VueCompositionApi)
call is made before calling any composition-api related functions.
import { computed, reactive } from "@vue/composition-api"
import { toReadonlyState } from "@/utils/composition"
interface GeneralStore {
token: string | null
isAuthenticated: boolean
isTranslationPresent: boolean
translationError: boolean
}
const state = reactive<GeneralStore>({
token: null,
isAuthenticated: false,
isTranslationPresent: false,
translationError: false,
})
export function useGeneralStore() {
const mutations = {
setToken: (token?: string) => {
state.token = token ?? null
},
setIsAuthenticated: (isAuthenticated: boolean) => {
state.isAuthenticated = isAuthenticated
},
setIsTranslationPresent: (isTranslationPresent: boolean) => {
state.isTranslationPresent = isTranslationPresent
},
setTranslationError: (translationError: boolean) => {
state.translationError = translationError
},
}
return {
...toReadonlyState(state),
...mutations,
}
}
After upgrading vue-demi to v6.0
the whole Vue2 application crashes on load with the following error:
Uncaught TypeError: Cannot read property 'observable' of undefined
at ht (vue-composition-api.esm.js:563)
ah gt (vue-composition-api.esm.js:673)
...
It seems Vue is undefined here...
// vue-composition-api.esm.js
function reactive(obj) {
if ((process.env.NODE_ENV !== 'production') && !obj) {
warn('"reactive()" is called without provide an "object".');
// @ts-ignore
return;
}
if (!(isPlainObject(obj) || isArray(obj)) ||
isRaw(obj) ||
!Object.isExtensible(obj)) {
return obj;
}
var observed = observe(obj); // FIXME: this call crashes due to Vue = undefined (line 673)
setupAccessControl(observed);
return observed;
}
// vue-composition-api.esm.js
function observe(obj) {
var Vue = getRegisteredVueOrDefault();
var observed;
if (Vue.observable) { // FIXME: Vue is undefined here (line 563)
observed = Vue.observable(obj);
}
else {
var vm = defineComponentInstance(Vue, {
data: {
$$state: obj,
},
});
observed = vm._data.$$state;
}
// in SSR, there is no __ob__. Mock for reactivity check
if (!hasOwn(observed, '__ob__')) {
def(observed, '__ob__', mockObserver(observed));
}
return observed;
}
For some reason, Vuelidate's useVuelidate()
function crashes on vue-demi
's getCurrentInstance()
, but only in Codesandbox (with Vue 2 only) and StackBlitz (any version of Vue).
I initially opened a Vuelidate issue, but they punted to vue-demi
.
Following the guide for using Vuelidate with Composition API, I'm seeing an error when useVuelidate()
is called:
index.js:27 TypeError: (0 , $csb__vuedemi.getCurrentInstance) is not a function
This seems to occur only in Codesandbox or StackBlitz. Running the same code in a Vue CLI scaffolded project works fine.
index.js:27 TypeError: (0 , $csb__vuedemi.getCurrentInstance) is not a function at useVuelidate (index.esm.js:580) at setup (App.vue:32) at mergedSetupFn (vue-composition-api.esm.js:1957) at eval (vue-composition-api.esm.js:1770) at activateCurrentInstance (vue-composition-api.esm.js:1708) at initSetup (vue-composition-api.esm.js:1769) at VueComponent.wrappedData (vue-composition-api.esm.js:1756) at getData (vue.common.dev.js:4754) at initData (vue.common.dev.js:4711) at initState (vue.common.dev.js:4650) at VueComponent.Vue._init (vue.common.dev.js:5010) at new VueComponent (vue.common.dev.js:5157) at createComponentInstanceForVnode (vue.common.dev.js:3307) at init (vue.common.dev.js:3136) at createComponent (vue.common.dev.js:6013) at createElm (vue.common.dev.js:5960) at Vue.patch [as __patch__] (vue.common.dev.js:6549) at Vue._update (vue.common.dev.js:3957) at Vue.updateComponent (vue.common.dev.js:4078) at Watcher.get (vue.common.dev.js:4490) at new Watcher (vue.common.dev.js:4479) at mountComponent (vue.common.dev.js:4085) at Vue.$mount (vue.common.dev.js:9084) at Vue.$mount (vue.common.dev.js:11989) at evaluate (main.js? [sm]:9) at V (eval.js:42) at ee.evaluate (transpiled-module.js:699) at ge.evaluateTranspiledModule (manager.js:297) at ge.evaluateModule (manager.js:268) at compile.ts:728 at c (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.t. [as next] (runtime.js:97) at r (asyncToGenerator.js:3) at u (asyncToGenerator.js:25)
Reproduction URL
https://codesandbox.io/s/usevuelidate-bug-getcurrentinstance-is-not-a-function-6rx9w
or
https://stackblitz.com/edit/vuelidate-bug-demo
To Reproduce
Steps to reproduce the behavior:
Create new Codesandbox for Vue 2 (or fork Vuelidate's official Vue 3 + Composition API Starter and switch Vue version to 2.x).
Add dependency for @vue/composition-api
, and install it from main.js
:
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi)
Open src/App.vue
, and copy Vuelidate guide's example code for the Composition API usage:
import { reactive, toRefs } from '@vue/composition-api'
import useVuelidate from '@vuelidate/core'
import { required, email } from '@vuelidate/validators'
export default {
setup () {
const state = reactive({
firstName: '',
lastName: '',
contact: {
email: ''
}
})
const rules = {
firstName: { required }, // Matches state.firstName
lastName: { required }, // Matches state.lastName
contact: {
email: { required, email } // Matches state.contact.email
}
}
const v$ = useVuelidate(rules, state)
return { ...toRefs(state), v$ }
}
}
See error in browser console
Expected behavior
The same output from Vuelidate's official Vue 3 + Composition API Starter.
Additional context
vue
2.6.14@vue/composition-api
1.0.0-rc.11@vuelidate/core
2.0.0-alpha.14 (also newer versions, including 2.0.0-alpha.19)@vuelidate/validators
2.0.0-alpha.12 (also newer versions, including 2.0.0-alpha.17)I have encountered an error when compiling a library to cjs
format and using it with Vue2.
Error:
Uncaught TypeError: _vue.use is not a function
at install (index.cjs.js:8)
at index.cjs.js:14
at chunk-4I6LKIR4.js?v=1e7b36e0:6
at match-sorter.esm.js:441
at chunk-4I6LKIR4.js?v=1e7b36e0:6
at index.js:12
at chunk-4I6LKIR4.js?v=1e7b36e0:6
at dep:vue-query_devtools:1
As seen on the screenshot Vue2 provides default export, which is only used on compositionApi currently, but not with the Vue itself.
I can fix said error by changing line 5
from : _vue = _vue || Vue
to: _vue = _vue.default || _vue || Vue.default || Vue
Reproduction steps:
npm i
npm pack
(npm link does not work somehow, there is a different error when using it which is not connected)cd examples/basic-vue-2.x/
npm i
npm pack
to example node_modulesnpm run dev
Am I missing some configuration part, or is it a real issue?
I can provide a PR if necessary with the mentioned fix.
Hi,
This issue because I've a problem trying to build our project on heroku:
error during build:
$ vite build
vite v2.1.2 building for production...
transforming...
β 2085 modules transformed.
'Vue2' is not exported by ../../node_modules/vue-demi/lib/index.esm.js, imported by ../../node_modules/vue-echarts/dist/index.esm.min.js
file: /tmp/build_8432c290/node_modules/vue-echarts/dist/index.esm.min.js:1:180
1: import{watch as e,inject as t,computed as n,unref as o,watchEffect as i,defineComponent as r,ref as a,shallowRef as u,toRefs as c,toRef as s,onMounted as l,onUnmounted as p,h as f,Vue2 as v,nextTick as d}from"vue-demi";import{throttle as h,init as g}from"echarts/core";import{addListener as O,removeListener as m}from"resize-detector";var y=function(){return(y=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)},b=["getWidth","getHeight","getDom","getOption","resize","dispatchAction","convertToPixel","convertFromPixel","containPixel","getDataURL","getConnectedDataURL","appendData","clear","isDisposed","dispose"];var j={autoresize:Boolean},x="ecLoadingOptions";var L={loading:Boolean,loadingOptions:Object};!function(e,t){void 0===t&&(t={});var n=t.insertAt;if(e&&"undefined"!=typeof document){var o=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&o.firstChild?o.insertBefore(i,o.firstChild):o.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}("x-vue-echarts{display:block;width:100%;height:100%}");var C=/^on[^a-z]/,U=function(e){return C.test(e)};v&&v.config.ignoredElements.push("x-vue-echarts");var z="ecTheme",D="ecInitOptions",E="ecUpdateOptions",w=r({name:"echarts",props:y(y({option:Object,theme:{type:[Object,String]},initOptions:Object,updateOptions:Object,group:String,manualUpdate:Boolean},j),L),inheritAttrs:!1,setup:function(r,f){var v=f.attrs,j=f.listeners,x=a(),L=u(),C=u(),z=t("ecTheme",null),D=t("ecInitOptions",null),E=t("ecUpdateOptions",null),w=n((function(){return C.value||r.option||Object.create(null)})),A=n((function(){return r.theme||o(z)||{}})),T=n((function(){return r.initOptions||o(D)||{}})),R=n((function(){return r.updateOptions||o(E)||{}})),B=c(r),P=B.autoresize,S=B.manualUpdate,k=B.loading,H=s(r,"theme"),I=s(r,"initOptions"),N=s(r,"loadingOptions"),W=n((function(){return function(e){var t={};for(var n in e)U(n)||(t[n]=e[n]);return t}(v)}));function F(e){if(!L.value&&x.value){var t=L.value=g(x.value,A.value,T.value);r.group&&(t.group=r.group);var n=j;n||(n={},Object.keys(v).filter((function(e){return 0===e.indexOf("on")&&e.length>2})).forEach((function(e){var t=e.charAt(2).toLowerCase()+e.slice(3);n[t]=v[e]}))),Object.keys(n).forEach((function(e){var o=n[e];o&&(0===e.indexOf("zr:")?t.getZr().on(e.slice(3).toLowerCase(),o):t.on(e.toLowerCase(),o))})),t.setOption(e||w.value,R.value),d(o),setTimeout(o)}function o(){t&&!t.isDisposed()&&t.resize()}}function Z(){L.value&&(L.value.dispose(),L.value=void 0)}var q=null;e(S,(function(t){"function"==typeof q&&(q(),q=null),t||(q=e((function(){return r.option}),(function(e){e&&(L.value?L.value.setOption(e,r.updateOptions):F())}),{deep:!0}))}),{immediate:!0}),e([H,I],(function(){Z(),F()}),{deep:!0}),i((function(){r.group&&L.value&&(L.value.group=r.group)}));var G=function(e,t){function n(n){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];if(e.value||t(),!e.value)throw new Error("ECharts is not initialized yet.");return e.value[n].apply(e.value,o)}}function o(e){return n(e)}return y(y({},(i=Object.create(null),b.forEach((function(e){i[e]=n(e)})),i)),{dispatchAction:o("dispatchAction"),getDataURL:o("getDataURL"),getConnectedDataURL:o("getConnectedDataURL")});var i}(L,F);!function(e,r,a){var u=t("ecLoadingOptions",{}),c=n((function(){return y(y({},o(u)),null==a?void 0:a.value)}));i((function(){var t=e.value;t&&(r.value?t.showLoading(c.value):t.hideLoading())}))}(L,k,N),function(t,n,o,i){var r=null,a=0;function u(){var e=o.value;return e?e.offsetWidth*e.offsetHeight:0}e([o,t,n],(function(e,t,n){var o=e[0],c=e[1],s=e[2];o&&c&&s&&(a=u(),r=h((function(){0===a?(c.setOption(Object.create(null),!0),c.resize(),c.setOption(i.value,!0)):c.resize(),a=u()}),100),O(o,r)),n((function(){r&&o&&(a=0,m(o,r))}))}))}(L,P,x,w),l((function(){r.option&&F()})),p(Z);var J=y({root:x,setOption:function(e,t){r.manualUpdate&&(C.value=e),L.value?L.value.setOption(e,y(y({},R.value),t)):F(e)},nonEventAttrs:W},G);return Object.defineProperty(J,"chart",{get:function(){return o(L)}}),J},render:function(){var e=y({},this.nonEventAttrs);return e.ref="root",e.class=e.class?["echarts"].concat(e.class):"echarts",f("x-vue-echarts",e)}});export default w;export{D as INIT_OPTIONS_KEY,x as LOADING_OPTIONS_KEY,z as THEME_KEY,E as UPDATE_OPTIONS_KEY};
^
2: //# sourceMappingURL=index.esm.min.js.map
error during build:
Error: 'Vue2' is not exported by ../../node_modules/vue-demi/lib/index.esm.js, imported by ../../node_modules/vue-echarts/dist/index.esm.min.js
at error (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:5307:30)
at Module.error (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:9716:16)
at Module.traceVariable (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:10104:29)
at ModuleScope.findVariable (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:8874:39)
at Identifier.bind (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:4042:40)
at LogicalExpression.bind (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:2744:23)
at LogicalExpression.bind (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:7824:15)
at ExpressionStatement.bind (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:2744:23)
at Program.bind (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:2740:31)
at Module.bindReferences (/tmp/build_8432c290/node_modules/rollup/dist/shared/rollup.js:9712:18)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed.
Exit code: 1
I actually don't understand why we have this, as the build is ok in local... π€
We use vue-3 and vitejs.
Any ideas?
Thanks.
Issue cross-posted in vue-echarts
I tried using vue-demi-switch 2 vue2
and defining "vue2": "npm:vue@2"
in my package.json, but when I run tests, the @vue/composition-api
breaks, because it imports Vue as var Vue = require('vue');
Do you have any advice on how to proceed with this? I saw vueuse/core
uses this approach but I couldnt see if you have a fix for this.
You can see this in https://github.com/vuelidate/vuelidate/tree/next
Hey, first of all great library it's something that's been much needed π so thanks a bunch
I tried to use it in https://github.com/MartinMalinda/vue-concurrency and I hit a blocker that it breaks my test suite.
I have a quick setup file that is being run before every test:
https://github.com/MartinMalinda/vue-concurrency/blob/master/test-utils/vue-setup.ts
This worked fine before but it doesn't do the trick now when I import from vue-demi
. I guess I do .use
on wrong Vue
. Perhaps there needs to be import { Vue } from 'vue-demi';
solely for testing purposes?
Hi, sorry that I'm creating a following issue to #22 but I don't have the right to re-open and I'm still a little bit stuck.
Problem
"export 'defineComponent | computed |. etc' was not found in 'vue'
Since my library exports components created using defineComponent
it doesn't work in a project with vue 2
Steps
README.md
in my library, changed vue
imports to vue-demi
, added the peerDependencies
, and installed everything.vue 2 demo
app ---> linknpm run serve
If I understand correctly it's necessary to publish the npm package for vue-demi to work when installing on a Vue 2 or 3 project, is not possible to test/debug locally without publishing it?.
Thanks in advance
Error: "TypeError: Cannot read property 'observable' of undefined"
I try to create a component for Vue3/2 with (vue-demi + Vite2) .
First, I'm focusing with Vue 2 setup, It's work fine in demo with directed import, but got error when in bundled lib (vite build)
https://github.com/sondh0127/vite-vue2-demi-reproduction/blob/d18773916b65c553c41c93b5823a4d797bcd0170/demo/App.vue#L11
Please take a look. Here is my vite config.
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createVuePlugin } from 'vite-plugin-vue2'
import WindiCSS from 'vite-plugin-windicss'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
// vue(),
createVuePlugin({}),
// WindiCSS(),
],
resolve: {
alias: {
'@': `${path.resolve(__dirname, 'src')}`,
},
dedupe: ['vue-demi'],
},
build: {
lib: {
name: 'VueInteractive',
entry: path.resolve(__dirname, 'src/main.ts'),
},
minify: false,
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue',
},
},
},
},
optimizeDeps: {
exclude: ['vue-demi'],
},
})
Reproduction: https://github.com/sondh0127/vite-vue2-demi-reproduction
i cannot get access to readonly from vue-demi
Catch error on first install every time...
OS:
yarn add vue-demi
yarn add v1.21.0
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
error /home/echo/ui-demi/node_modules/vue-demi: Command failed.
Exit code: 1
Command: node ./scripts/postinstall.js
Arguments:
Directory: /home/echo/ui-demi/node_modules/vue-demi
Output:
yarn add v1.21.0
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
ββ @vue/[email protected]
info All dependencies
ββ @vue/[email protected]
Done in 13.29s.
internal/fs/utils.js:220
throw err;
^
Error: ENOENT: no such file or directory, open '/home/echo/ui-demi/node_modules/vue-demi/lib/index.cjs.js'
at Object.openSync (fs.js:440:3)
at Object.writeFileSync (fs.js:1265:35)
at switchVersion (/home/echo/ui-demi/node_modules/vue-demi/scripts/postinstall.js:31:6)
at Object.<anonymous> (/home/echo/ui-demi/node_modules/vue-demi/scripts/postinstall.js:46:3)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: '/home/echo/ui-demi/node_modules/vue-demi/lib/index.cjs.js'
}
When buildοΌI get it
(!) Conflicting re-exports
node_modules/vue-demi/lib/index.esm.js re-exports 'version' from both node_modules/vue-demi/lib/index.esm.js and node_modules/@vue/composition-api/dist/vue-composition-api.esm.js (will be ignored)
The code
export * from '@vue/composition-api'
export {
Vue,
isVue2,
isVue3,
version,
install,
}
Hi,
I'll be glad to change direction of text to "RTL" for hebrew language.
Best
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.