Problem using sweetalert2 and filepond in Laravel 9.2 - javascript

Hell guys ,
I am using Laravel 9 and I want to use sweetalert2 and filepond in my project.
I installed the mentioned plugins through npm.
This is my app.js file
import './bootstrap';
import Alpine from 'alpinejs';
import * as FilePond from 'filepond';
import Swal from 'sweetalert2';
import 'filepond/dist/filepond.min.css';
window.Alpine = Alpine;
window.FilePond = FilePond;
window.Swal = Swal;
I also included this in head tag
#vite(['resources/css/app.css', 'resources/js/app.js'])
I also run this command in terminal without any error.
npm run dev
This is my script tag for sweetalert2.
#if(Session::has('status'))
// This works but I don't want it -> {{-- <script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script> --}}
// This one is not working
<script>
Swal.fire({
toast: true,
position: 'top-end',
icon: 'success',
title: "{{Session::get('status')}}",
showConfirmButton: false,
timer: 1500
})
</script>
#endif
This is my script tag for filepond.
<script>
// Get a reference to the file input element
const inputElement = document.querySelector('input[type="file"]');
// Create a FilePond instance
const pond = FilePond.create(inputElement);
</script>
I also get this error after using sweetalert2 or filepond
Uncaught ReferenceError: Swal is not defined
Uncaught ReferenceError: FilePond is not defined
Is it because of the vite?
How can I fix this?
I used sweetalert2 in my previous project in Laravel 8.x and that was working and the app.js file looked like this.
require('./bootstrap');
window.Swal = require('sweetalert2')
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
This require function is not working in Laravel 9.2 and I get the same error require is not defined.

The problem was my I was trying to access Swal and FilePond before they have been loaded into the window. A fix for that is to make sure you only execute some JavaScript after the window and its properties have loaded.
window.addEventListener('load', () => {
// window has loaded...
});
Or you can listen for when the document has finished loading.
document.addEventListener('DOMContentLoaded', () => {
// document has loaded...
});

Related

Elixir Phoenix serve Javascript from /priv/static

I am currently fighting esbuild in my phoenix project. I have a heex template on which I want to use Trumbowyg as a text editor. First I tried to import the javascript file via vendoring it and doing import trumbowyg from '../vendor/trumbowyg.min.js in app.js.
I thought this would work because it did for AlpineJs. But it didn't. It complained about missing jQuery. So I vendored jQuery the same way: import {jQuery, $} from '../vendor/jquery.min.js. But no success. Same error message Uncaught ReferenceError: $ is not defined.
Then I had the idea to fix it via importing the scripts in the template withing <script> tags. SO i just threw the two js files into the /priv/static/assets/ folder. This worked in development with the following tags:
<script type="text/javascript" src={Routes.static_path(#conn, "/assets/jquery.min.js")}></script>
<script type="text/javascript" src={Routes.static_path(#conn, "/assets/trumbowyg.min.js")}></script>
But this stopped working in production (I use the docker deploy method). Then I tried using some kind of Plug.Static implementation but I did not get it to work.
So my question now is: How can I make those scripts load in a production environment? Even better would be to know how to configure esbuild to use deploy the script files correctly. I don't know what to change, because my AlpineJs import is working fine.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
import Alpine from "../vendor/alpine.min"
window.Alpine = Alpine;
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
dom: {
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
window.Alpine.clone(from, to)
}
}
}
})
// Show progress bar on live navigation and form submits
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", info => topbar.show())
window.addEventListener("phx:page-loading-stop", info => topbar.hide())
// connect if there are any LiveViews on the page
liveSocket.connect()
// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket
That's the content of my app.js file. But like I said, adding: import trumbowyg from '../vendor/trumbowyg.min.js or import {jQuery, $} from '../vendor/jquery.min.js gets me errors like Uncaught ReferenceError: $ is not defined and Uncaught ReferenceError: jQuery is not defined.
Every help is appreciated. Thanks in advance.

Uncaught ReferenceError: Glide is not defined - Although Glide loaded in app.js like all others

In a Laravel 9 project I am loading Glide.js via my app.js file:
import "./bootstrap";
import flatpickr from "flatpickr";
import Alpine from "alpinejs";
import Glide from "#glidejs/glide";
window.Alpine = Alpine;
window.flatpickr = flatpickr;
Alpine.start();
If I initialise the Glide object in the same file with:
new Glide(".glide", {hoverpause:true, autoplay:2000}).mount();
It works ok on the page I want it on, however it stops Alpine working on other pages.
I assumed that by adding it to the Window object
window.Glide = Glide;
I could simply declare it on the page I want it but I get the
Uncaught ReferenceError: Glide is not defined error.
I've also tried importing via cdn in a script tag placed on my home view
<script src="https://unpkg.com/#glidejs/glide#3.6.0/dist/glide.js"></script>
<script>
new Glide(".glide", {
hoverpause: true,
autoplay: 2000,
perView: 3,
}).mount();
</script>
But this tells me that [Glide warn]: Root element must be a existing Html node and doesn't work either.
Js isn't my strong suit by a long shot and I have a lot to read up on and learn but would somebody be so kind as to give me some pointers?
Thanks in advance.
I solved this issue by only instanciating the Glide object if the target element exists.
if (document.querySelector(".glide") !== null) {
new Glide(".glide", {
hoverpause: true,
autoplay: 2000,
perView: 3,
}).mount();
}

How to import octokit in browser

tried to follow an example from this. To import octokit I first pasted the following lines into my html document as stated by adding the following lines:
<script type="module">
import { Octokit } from "https://cdn.skypack.dev/#octokit/core";
</script>
This just resulted in an Uncaught (in promise) ReferenceError: Octokit is not defined. Moving the line in script tags directly into the script.js file above the code just made one of the main functions appear as undefined (it handled a button click that authenticated a google account and then retrieved data from google sheets via the sheets API).
I then tried all this with new html and js files, adding that code directly to the html had the same result but this time adding it to the start of the js file gives a import declarations may only appear at top level of a module script.js:1
Don't really know what to do from here so any help would be appreciated. Did find this though but it just says the issue is fixed?
I think the best solution is to write your script logic in a separate javascript file, and then import that file in your html at the end of body element.
Here is an example of getting your repositories from GitHub:
repos.js
import { Octokit } from "https://cdn.skypack.dev/octokit";
import { config } from "./config.js";
const GIT_KEY = config.API_KEY;
export const octokit = new Octokit({
auth: GIT_KEY,
});
const repo = await octokit.request(
"GET /users/{username}/repos{?type,sort,direction,per_page,page}",
{
username: "your_username",
}
);
console.log(repo);
repos.html:
<body>
...
<script type="module" src="repos.js"></script>
</body>

Vue 3 mobile event listeners and swipe

In Vue 3, I want to trigger a function when a user swipes left / right. (I made a calendar and interested in having months changed on swiping)
I found this package: https://github.com/robinrodricks/vue3-touch-events (npm install vue3-touch-events) but it's not working and I get the following errors:
and imported the relevant packages in main.js:
import Vue from "vue";
import Vue3TouchEvents from "vue3-touch-events";
and in public/index.html:
<script src="https://raw.githubusercontent.com/robinrodricks/vue3-touch-events/master/index.js"></script>
after that, in main.js
If registered as:
createApp(App)
.use(Vue3TouchEvents)
then I get the error: "Maximum recursive updates exceeded in component ..."
And the event won't be fired.
If registered as
Vue.use(Vue3TouchEvents);
then I get the error "export 'default' (imported as 'Vue') was not found in 'vue'"
And the event still won't be fired
What's wrong? How to implement it right or make a solution in another way?
(#starttouch and mobile event listeners seems to not be supported in Vue 3)
I Think You Installed It Wrong Way
npm cache clean --force
npm install vue3-touch-events
Also Remove That script src line from index.html.
I Hope This Will Help Your Query.
I solved the problem in this way, please note that only the function name needs to be passed
main.js
import Vue3TouchEvents from "vue3-touch-events";
const app = createApp(App);
app.use(Vue3TouchEvents);
Component.vue
// script setup
const doSwipeLeft = () => {
// some code
};
const doSwipeRight = () => {
// some code
};
//template
<Component
v-touch:swipe.left="doSwipeLeft"
v-touch:swipe.right="doSwipeRight"
>

How to use a script library across modules

I'm trying to use a 3rd party library "emailjs.com" in a react project i'm working on (uses webpack to bundle the modules).
The issue i'm having is that I need to initialise the library in the html like so
<script type="text/javascript" src="https://cdn.emailjs.com/dist/email.min.js"></script>
<script type="text/javascript">
(function(){
emailjs.init("YOUR USER ID");
})();
</script>
https://www.emailjs.com/docs/api-reference/emailjs-send/
Now I need to call the library in my react component on button click
_submitForm(e) {
e.preventDefault();
alert("Button Click works"); // This is printed fine
// Undefined
emailjs.send("my_service","my_template",{
name: "James",
notes: "Check this out!"
});
}
However I get an emailJS is undefined error (as I expected). My question is what the correct way to give my "form" component scope of the emailJS module.
I've tried creating "emailjs.js"
export default () => {
// Minified email code in here
}
Then importing it like so
import emailjs from '../PathToComponent/emailjs';
However this is failing to compile, i'm getting the error "Module not found: Error: Cannot resolve module 'vertx'", however all dependencies should be contained inside the emailJS minified file?
If anyone has any suggestions or perhaps a better way to send my e-mails from within a react componenet please let me know!
Form component: http://pastebin.com/x5KVPKXm
emailJS Export: http://pastebin.com/NA40ZrTT

Categories

Resources