how to solve this error? "lazy-load in not a function" - lazy-loading

I use isotope plugin and lazy-sizes to build a photo gallery. but lazy-loading doesn't work and i get this error: "lazyload is not a function".
is there any idea for this issue and how to implement both plugins together?
npm install lazysizes --save
npm install isotope-layout --save
this is my code:
import $ from 'jquery';
import Isotope from 'isotope-layout';
import jQueryBridget from 'jquery-bridget';
import imagesLoaded from 'imagesloaded';
import lazyload from 'lazysizes';
jQueryBridget( 'isotope', Isotope, $ );
jQueryBridget( 'imagesLoaded', imagesLoaded, $ );
class isotopeGallrey {
constructor() {
this.Grid = $(".grid");
this.itemImage = $(".grid-item img");
this.createIsotope();
}
createIsotope() {
var that = this;
this.Grid.imagesLoaded(function() {
that.Grid.isotope({
columnWidth: '.grid-sizer',
itemSelector: '.grid-item',
containerClass: 'isotope',
layoutMode: 'masonry',
percentPosition: true
});
that.itemImage.lazyload({
effect: 'fadeIn'
});
that.itemImage.trigger('scroll');
});
}
}
export default isotopeGallrey;

Related

Unable to resolve module crypto

I am attempting to implement WalletConnect V1 in my React-Native Wallet app. However, whenever I use the following import:
import WalletConnect from "#walletconnect/client";
I get the following error:
Unable to resolve module crypto from /Users/<my-name>/<company-name>/<client-name>/<app-name>/node_modules/#walletconnect/randombytes/dist/cjs/node/index.js: crypto could not be found within the project or in these directories:
node_modules
I tried following some solutions but installing crypto-js and crypto-js#3.3.0 both did not fix the issue. I also already have react-native-crypto installed in my application.
Any help figuring out what I need to do to resolve this error would be amazing!
Just add custom resolver to your metro config
// metro.config.js
module.exports = {
resolver: {
extraNodeModules: {
crypto: require('react-native-cyrpto'),
},
},
};
Unfortunately crypto depends on other nodejs packages like: net, tls, fs and etc. Recommend using https://github.com/parshap/node-libs-react-native which polyfills node packages inside react-native
Docs
tldr;
nom install node-libs-react-native
// metro.config.js
module.exports = {
resolver: {
extraNodeModules: require('node-libs-react-native'),
},
};
I managed to solve this thanks to this post (https://github.com/parshap/node-libs-react-native/issues/23)
yarn add react-native-get-random-values
const nodelibs = require("node-libs-react-native");
nodelibs.crypto = `${__dirname}/src/crypto.js`;
module.exports = {
resolver: {
extraNodeModules: nodelibs,
},
};
Then created my own crypto.js file
// src/crypto.js
'use strict'
import { Buffer } from 'buffer';
const { NativeModules } = require('react-native');
const randomBytes = (size) => {
if (NativeModules.RNGetRandomValues) {
return Buffer(NativeModules.RNGetRandomValues.getRandomBase64(size));
} else {
throw new Error('Native module not found')
}
};
exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = randomBytes;

Configuring Pusher on Vue3

I have a project in Vue3 and want to implement a real time API or a web socket. So I attempted to use pusher using Vue third part libraries which are pusher-vue and vue-pusher. Using pusher-vue I am getting the error: Uncaught TypeError: e.prototype is undefined. Using vue-pusher I am getting the error: Uncaught TypeError: Vue.prototype is undefined. The following are the libraries' configurations:
PUSHER VUE
Component.vue
export default{
channels: {
applications_channel: {
subscribeOnMount: true,
subscribed(){
console.log("Some text")
},
bind:{
add_application_event(data){
console.log(data)
}
}
}
}
}
main.js
createApp(App)
.use(PusherVue, {
app_key: "MY_KEY",
cluster: 'MY_CLUSTER',
debug: true,
debugLevel: "all"
})
.mount("#app")
VUE PUSHER
Component.vue
export default{
read(){
var channel = this.$pusher.subscribe('applications-channel')
channel.bind('add-application-event', ({ log }) => {
console.log(log);
})
}
}
main.js
createApp(App)
.use(require("vue-pusher"), {
api_key: "MY_KEY",
options: {
cluster: 'MY_CLUSTER',
ecrypted: true,
}
})
.mount("#app")
May you please help with how can I configure this on Vue3 or recommend any beginner friendly alternatives to achieve the same functionality on Vue3.
Both pusher-vue and vue-pusher were built for Vue 2, so you need to use the Vue 3 migration build to make the library work in your project.
To setup your Vue CLI scaffolded project:
Install the Vue compatibility build and SFC compiler that matches your Vue build version (i.e., install #vue/compat#^3.1.0 and #vue/compiler-sfc#^3.1.0 if you have vue#^3.1.0 in package.json):
npm i -S #vue/compat#^3.1.0
npm i -S #vue/compiler-sfc#^3.1.0
Configure Webpack to alias vue to the #vue/compat build, and set vue-loader's compatibility mode to Vue 2:
// vue.config.js
module.exports = {
chainWebpack: config => {
config.resolve.alias.set('vue', '#vue/compat')
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
return {
...options,
compilerOptions: {
compatConfig: {
MODE: 2
}
}
}
})
}
}
demo: vue-pusher in Vue 3 w/migration build
However, vue-pusher 1.1.0 seems to only expose a new instance of Pusher (from pusher-js) as this.$pusher on the Vue instance. That code could easily be migrated to Vue 3 as a plugin:
// plugins/pusher.js
export default (app, { apiKey, ...options }) => {
const Pusher = require('pusher-js')
app.config.globalProperties.$pusher = new Pusher(apiKey, options)
}
// main.js
const { createApp } = require('vue')
import App from './App.vue'
import PusherPlugin from './plugins/pusher'
createApp(App)
.use(PusherPlugin, { apiKey: 'YOUR_API_KEY', cluster: 'YOUR_CLUSTER' })
.mount('#app')
demo: pusher-js in Vue 3

How can I display the current app version from package.json to the user using Vite?

With create-react-app one could use process.env.REACT_APP_VERSION for this.
Is there an equivalent in Vite?
For React & TypeScript users:
Add a define to your vite.config.ts:
import react from '#vitejs/plugin-react';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [react()],
define: {
APP_VERSION: JSON.stringify(process.env.npm_package_version),
},
});
If you haven't got one already, define a vite-env.d.ts or env.d.ts and add a declare:
declare const APP_VERSION: string;
You'll now be able to use the variable APP_VERSION anywhere in your code & Vite will substitute it at compile time.
Note: You may need to restart your TS server for the declaration to be picked up by intellisense:
VSCode MacOS: ⌘ + ⇧ + P > Restart TS Server
VSCode Windows: ctrl + ⇧ + P > Restart TS Server
EDIT: For TypeScript, see Jamie's answer to set the types.
If you want to use plugin, see Adarsh's answer
But it's very easy to implement it yourself.
You can use define in vite.config.js. Read about it here
vite.config.js
export default {
plugins: [vue()],
define: {
'__APP_VERSION__': JSON.stringify(process.env.npm_package_version),
}
}
component.vue
<template>
<div>{{ version }}</div>
</template>
<script>
export default {
data () {
version: __APP_VERSION__
},
}
</script>
or with <script setup>
<script setup>
const version = __APP_VERSION__
</script>
<template>
<div>{{ version }}</div>
</template>
You should be able to change '__APP_VERSION__' as long as it doesn't conflict with javascript syntax or other variables.
If you don't want to use define, there is a vite plugin for just this.
https://www.npmjs.com/package/vite-plugin-package-version
// vite.config.js
import loadVersion from 'vite-plugin-package-version';
export default {
plugins: [loadVersion()],
};
Will inject import.meta.env.PACKAGE_VERSION with the version specified in your package.json.
Vite 4, React, Typescript setup
This worked for me.
I imported package.json in vite.config.ts and defined a PACKAGE_VERSION environment variable.
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
import packageJson from './package.json';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
define: {
'import.meta.env.PACKAGE_VERSION': JSON.stringify(packageJson.version)
}
})
I added "resolveJsonModule": true to the compiler options of tsconfig.node.json.
I added "./package.json" to the include array of tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true
},
"include": ["vite.config.ts", "./package.json"]
}
In order to make intellisense work for PACKAGE_VERSION, I added it to vite-env.d.ts
interface ImportMetaEnv {
readonly PACKAGE_VERSION: string;
// more env variables...
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
I could use {import.meta.env.PACKAGE_VERSION} anywhere in my react app to show the package version.
This worked for me:
import { version } from '../../package.json'
In case anyone is interested, this automatically increases the version in package.json and makes it available to the application.
import { defineConfig } from 'vite';
const increasePackageVersion = () => {
try {
const fs = require('fs');
const path = require('path');
const packageFilePath = path.join(__dirname, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageFilePath, 'utf8'));
packageJson.version = packageJson.version.replace(/(\d+)$/, (match, p1) => {
return parseInt(p1) + 1;
}
);
fs.writeFileSync(packageFilePath, JSON.stringify(packageJson, null, 2));
console.log('New version is', packageJson.version);
} catch (error) {
console.log('Error in increasePackageVersion', error);
}
};
export default defineConfig({
build: {
lib: {
entry: 'src/main.js',
formats: ['es']
}
},
plugins: [
increasePackageVersion()],
define: {
'__APP_VERSION__': JSON.stringify(process.env.npm_package_version),
}
});
console.log(__APP_VERSION__);
Below Answer includes
Secure Way of Importing Vue version.
Incrementing semantic versions using npm commands
Secure and Semantic Way of Versioning using npm and env

How do I mock this Vue injection?

I have a Vue 3 component that, when mounted in tests, cause warnings:
console.warn node_modules/#vue/runtime-core/dist/runtime-core.cjs.js:40
[Vue warn]: injection "Symbol(VueToastification)" not found.
at <ModifyJob ref="VTU_COMPONENT" >
at <VTUROOT>
I assume it's this one complaining https://github.com/Maronato/vue-toastification/blob/master/composition/index.js#L30.
I have nearly 100 of these warnings, so it's kind of hard to read test-run output. I've tried to mock provide for this dependency, but I can't seem to succeed:
let provide = {}
provide[VueToastification] = VueToastification
provide['VueToastification'] = VueToastification
provide[Symbol(VueToastification)] = VueToastification
provide[Symbol('VueToastification')] = VueToastification
provide['Symbol(VueToastification)'] = VueToastification
let options = {
global: {
provide: provide,
}
}
mount(ModifyJob, options)
Is this some Vue2/Vue3 incompatibility or do I just not understand the docs at https://vue-test-utils.vuejs.org/v2/api/#global-provide ? Can someone help me get rid of these warnings, ideally by allowing me to inject a mock so I can test that toasts are made?
That error actually indicates that the plugin isn't installed in the test Vue instance. You could make VueToastification available to the component under test through the global.plugins mounting option:
import { shallowMount } from '#vue/test-utils'
import MyComponent from '#/components/MyComponent.vue'
import VueToastificationPlugin from 'vue-toastification'
it('initializes', () => {
shallowMount(MyComponent, {
global: {
plugins: [VueToastificationPlugin]
}
})
})
Alternatively, if you want to verify that toast() (from VueToastification's useToast()) is called, you could mock vue-toastification:
import { shallowMount } from '#vue/test-utils'
import MyComponent from '#/components/MyComponent.vue'
jest.mock('vue-toastification')
it('should call toast', () => {
const toast = jest.fn()
require('vue-toastification').useToast.mockReturnValueOnce(toast)
shallowMount(MyComponent).vm.showToast()
expect(toast).toHaveBeenCalled()
})
I solved setting a global list of plugins according to https://next.vue-test-utils.vuejs.org/api/#config-global:
// In a jest.setup.js file
import { config } from "#vue/test-utils";
import VueToastificationPlugin from "vue-toastification";
config.global.plugins = [VueToastificationPlugin];
// In your jest.config.js
module.exports = {
...
setupFilesAfterEnv: ["./jest.setup.js"],
};

Using quill modules with vue2-editor and webpack mix

I'm currently using vue2-editor and importing quill modules and registering them as per documentation.But getting error window.Quill is undefined.
I've tried webpack plugin mix to include window.Quill and Quill but still error remains the same.
In my vue component
import { VueEditor } from "vue2-editor";
import { Quill } from "quill";
import { ImageDrop } from "quill-image-drop-module";
import { ImageResize } from "quill-image-resize-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize);
And in my webpack mix
mix.extend('foo',new class{
webpackPlugins(){
return new webpack.ProvidePlugin({
"window.Quill": "quill/dist/quill.js",
Quill: "quill/dist/quill.js"
});
}
});
Uncaught TypeError: Cannot read property 'imports' of undefined
which is from window.Quill.imports
You need to get REALY working files from https://www.jsdelivr.com/package/npm/quill-image-resize-vue:
Just install npm i --save quill-image-resize-vue
and use another file:
import { VueEditor,Quill } from 'vue2-editor'
import ImageResize from 'quill-image-resize-vue';
import { ImageDrop } from 'quill-image-drop-module';
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize);
export default {
name: 'MainForm',
components: { VueEditor},
data() {
return {
content: '<h2>I am Example</h2>',
editorSettings: {
modules: {
imageDrop: true,
imageResize: {},
}
}
}
},
//........
}
For me got fixed after changing
import { ImageResize } from "quill-image-resize-module";
to
import ImageResize from "quill-image-resize-module";