new to all these modern day frameworks
I'm trying to get this javascript library to work in my Vue component: https://clipboardjs.com
I can see it is integrated into my public/js/app.js file when Mix runs - but I cannot seem to be able to reference it from within my .vue (component) file
Can anyone give me a step by step guide on how to get this to integrate into my project please:
resources/js/app.js file
import './clipboard';
the clipboard.js file is located at:
resources/js/clipboard.js
Mix webpack.mix.js file:
mix.js("resources/js/app.js", "public/js")
.js("resources/js/clipboard.js", "public/js")
.vue()
.postCss("resources/css/app.css", "public/css", [
require("tailwindcss"),
]);
My Vue component (method section):
<script>
export default {
props: ['mediaDetails'],
data() {
return {
}
},
methods: {
copyPassword() {
alert("copy");
var password = document.getElementById('#password');
alert('1');
var clipboard = new ClipboardJS(password);
alert('2');
}
}
the alert('2') never fires due to the clipboard assignemnet failing
First, in your webpack.mix.js file, remove the line .js("resources/js/clipboard.js", "public/js")
Install the clipboard package: npm install clipboard
In your Vue component, import the package in order to use it:
<script>
import ClipboardJS from 'clipboard';
export default {
props: ['mediaDetails'],
data() {
return {
}
},
methods: {
copyPassword() {
alert("copy");
var password = document.getElementById('#password');
alert('1');
var clipboard = new ClipboardJS(password);
alert('2');
}
}
BTW You have a typo error in document.getElementById('#password'), it should be document.getElementById('password')
Related
Hey I am playing around with web3 inside react as a client application (using vite react-ts) and trying to call web3.eth.net.getId() but this will throw me an error that callbackify is not a function I digged a little and found an old issue on the github which states that older versions of Nodejs.util (prior version 0.11) didn't have this function. So I checked the package.json where the error occurs (web3-core-requestmanager) it has "util":"^0.12.0", so callbackify should be available.
In fact when I am looking at their imports, they seem to be able to import it:
(following code is ./node_modules\web3-core-requestmanager\src\index.js
const { callbackify } = require('util');
but when they want to use it, callbackify is undefined
//RequestManager.prototype.send function
const callbackRequest = callbackify(this.provider.request.bind(this.provider));
I tried to play around with the dependencies and tried different versions of web3.js (1.7.3; 1.6.0; 1.5.1) all of them had the same util dependency (0.12.0).
My code in all this matter looks like this:
class Blockchain {
public blockchainBaseUrl: string;
public web3;
public provider;
public account: string = '';
public contract: any;
constructor() {
if (process.env.REACT_APP_BLOCKCHAIN_BASE_URL === undefined) {
throw new Error('REACT_APP_BLOCKCHAIN_BASE_URL is not defined');
}
this.provider = window.ethereum;
if (this.provider === undefined) {
throw new Error('MetaMask is not installed');
}
this.setUpInitialAccount();
this.addEthereumEventListener();
this.blockchainBaseUrl = process.env.REACT_APP_BLOCKCHAIN_BASE_URL;
this.web3 = new Web3(Web3.givenProvider || this.blockchainBaseUrl);
this.setContract();
}
async setContract() {
// error comes from the next line
const networkId = await this.web3.eth.net.getId();
this.contract = new this.web3.eth.Contract(
// #ts-ignore
Token.abi,
// #ts-ignore
Token.networks[networkId].address
);
}
}
I also was told that I should simply add a .catch() to web3.eth.net.getId() but this did nothing. Am I doing something wrong or is this a dependency problem? If anyone could point me in the right direction I would really appreciate it. Do I need to expose the util API to the browser somehow? To me, it seems that the API is simply not available.
This is should be the relevant part of my vite.config.ts:
import GlobalsPolyfills from '#esbuild-plugins/node-globals-polyfill';
import NodeModulesPolyfills from '#esbuild-plugins/node-modules-polyfill';
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react';
export default defineConfig({
plugins: [
react(),
],
optimizeDeps: {
esbuildOptions: {
plugins: [
NodeModulesPolyfills(),
GlobalsPolyfills({
process: true,
buffer: true,
}),
],
define: {
global: 'globalThis',
},
},
},
});
Here is my complete vite config
https://pastebin.com/zvgbNbhQ
Update
By now I think that I understand the issue - it seems that it is a VIte-specific problem and I need to polyfill the NodeJs.util API. I am already doing this (at least I thought). Perhaps someone can provide some guidance on what I am doing wrong with my config?
Update 2
I actually have now the util API inside the browser, but it is still giving me the same error. This is my new config:
https://pastebin.com/mreVbzUW I can even log it out:
Update 3
SO I am still facing this issue - I tried a different approach to polyfill I posted the update to the github issue https://github.com/ChainSafe/web3.js/issues/4992#issuecomment-1117894830
Had similar problem with vue3 + vite + we3
It's started from errors: process in not defined than Buffer is not defined and finally after I configure polyfill I came to callbackify is not defined
Did a lot of researches and finally solved this issue with next trick:
Rollback all polyfill configurations
Add to the head html file
<script>window.global = window;</script>
<script type="module">
import process from "process";
import { Buffer } from "buffer";
import EventEmitter from "events";
window.Buffer = Buffer;
window.process = process;
window.EventEmitter = EventEmitter;
</script>
vite.config.ts
import vue from '#vitejs/plugin-vue'
export default {
resolve: {
alias: {
process: "process/browser",
stream: "stream-browserify",
zlib: "browserify-zlib",
util: 'util'
}
},
plugins: [
vue(),
]
}
add these dependencies browserify-zlib, events, process, stream-browserify, util
Source https://github.com/vitejs/vite/issues/3817#issuecomment-864450199
Hope it will helps you
Im having a simple import problem in my VueJS 3 app. I have looked at this answer: Vue 3 Composition API Provide/Inject not working in Single File Components but did not find an answer.
I am importing my external file in main.js: import * as myService from "./services/myService.js";
Then also in main.js: app.provide("myService", myService);
And then in my component I have:
<script>
export default {
name: "MyComponent",
props: {
...
},
methods: {
myFunc: function(){
var result = myService.serviceFunction();
}
},
data: function(){
return {
...
}
},
inject: ["myService"]
}
</script>
But where I have var result = myService.serviceFunction(); gives me the error that myService is undefined.
If I call var result = myService.serviceFunction(); in main.js there is no error and the function is called correctly, so the problem must be with the VueJS injection.
What have I done wrong?
You should add this to get access to the injected item :
methods: {
myFunc: function(){
var result = this.myService.serviceFunction();
}
},
I'm trying to use BeePlugin package in a Rails project and it raised the question of how to import properly a library using Webpacker?
I added jQuery but somehow I can't add bee-plugin.
I wanna be able to import just what I need and only in the file I need it
So far what I did was
Install the library with yarn yarn add #mailupinc/bee-plugin
Created a new file to add my code and import it in application.js import ./bee
In the new file import my library. I have tried
import "#mailupinc/bee-plugin"
import Bee from "#mailupinc/bee-plugin"
import * as Bee from "#mailupinc/bee-plugin"
const Bee = require "#mailupinc/bee-plugin"
None of them seem to work. Why?
I always get Uncaught ReferenceError: Bee is not defined
For reference
application.js
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
import "./bee";
webpack/environment.js
const { environment } = require('#rails/webpacker')
const webpack = require("webpack");
// Avoid using require and import and alias jquery
environment.plugins.append(
"Provide",
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
})
);
module.exports = environment
bee.js
import Bee from "#mailupinc/bee-plugin";
function initBee() {
$.ajax({ url: "/editor/token", success: startBee });
}
function beeConfig() {
return {...} // Config params
}
function startBee(auth) {
const beeInstance = Bee.create(auth, beeConfig(), (instance) => {
$.ajax({
url: $("#bee-plugin-container").data("template"),
success: (template) => instance.start(template),
});
return instance;
});
}
$(document).on("turbolinks:load", initBee);
So there was nothing wrong with the import.
Turns out the library will asynchronously import an external script during the initialisation of an instance and that script was where the create method was defined (source code here)
The file now looks like
import Bee from "#mailupinc/bee-plugin";
function initBee() {
$.ajax({ url: "/editor/token", success: startBee });
}
function beeConfig() {
return {...}
}
function startBee(auth) {
$.ajax({
url: $("#bee-plugin-container").data("template"),
success: (template) => new Bee(auth).start(beeConfig(), template),
});
}
$(document).on("turbolinks:load", initBee);
How can I dynamically bundle a module/object into my RollupJs output file? I have tried a ton off different options but can not get the expected output I am looking for.
I put together a short sample project below to help illustrate what I am looking for. The expected output should print "Hello John Doe" from the overrideApp object that is dynamically injected as a dependency.
src/app.js
export default {
sayHello: function() {
console.log('Hello Mr.Roboto')
},
sayGoodBye: function() {
console.log('Goodbye Mr.Roboto')
}
}
index.js
import app from './src/app.js'
import overrideApp from 'overrideApp'
export default { ...app, ...overrideApp }.sayHello()
.rollup.config.js
let overrideApp = {
sayHello: function() {
console.log('Hello John Doe')
}
}
export default [
{
input: 'index.js',
external: ['overrideApp'], // This is not working, expecting to pass overrideApp to index.js
output: {
file: './dist/app.js',
format: 'umd',
name: 'bundle',
}
}
]
This is totally correct your mixing here a lot of stuff together that does not work together.
You are looking for a virtual module
Install
npm install #rollup/plugin-virtual --save-dev
Usage
Note. Use this plugin before any others such as node-resolve or commonjs, so they do not alter the output.
Suppose an entry file containing the snippet below exists at src/entry.js, and attempts to load batman and src/robin.js from memory:
// src/entry.js
import batman from 'batman';
import robin from './robin.js';
console.log(batman, robin);
Create a rollup.config.js configuration file and import the plugin:
import virtual from '#rollup/plugin-virtual';
export default {
entry: 'src/entry.js',
// ...
plugins: [
virtual({
batman: `export default 'na na na na na'`,
'src/robin.js': `export default 'batmannnnn'`
})
]
};
https://github.com/rollup/plugins/edit/master/packages/virtual
I'm creating an application based on gatsby framework, but I have problem with initialize gatsby theme. From official documentation:
https://www.gatsbyjs.org/tutorial/part-three/
import Typography from 'typography';
import fairyGateTheme from 'typography-theme-github';
const typography = new Typography(fairyGateTheme);
export const { scale, rhythm, options } = typography;
export default typography;
But typography-theme-github import has dotted underline when I hovered mouse on it I have got this tip:
Could not find a declaration file for module 'typography-theme-github'. '/Users/jozefrzadkosz/Desktop/hello-world/node_modules/typography-theme-github/dist/index.js' implicitly has an 'any' type.
Try npm install #types/typography-theme-github if it exists or add a new declaration (.d.ts) file containing declare module 'typography-theme-github';ts(7016)
When I run gatsby develop I'm getting this error:
Error: Unable to find plugin "undefined". Perhaps you nee d to install its package?
EDIT
I have looked on this file node_modules/typography-theme-github/dist/index.js and I found one similar issue:
var _grayPercentage = require("gray-percentage");
This require has exactly same tip as my theme import.
SECOND EDIT
Gatsby.config.js
module.exports = {
plugins: [
[`gatsby-plugin-sass`],
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography`
}
}
]
};
I notice you placed gatsby-plugin-sass in an array, which is why gatsby didn't recognize it:
module.exports = {
plugins: [
- [`gatsby-plugin-sass`], <-- error
+ `gatsby-plugin-sass`,
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography`
}
}
]
};
This is probably not a problem with gatsby-plugin-typography.