Laravel 9 - using vite to do a js import within a blade template - javascript

I am trying out Laravel 9 with Vite, but without(!) a frontend framework (like Vue or React).
I am trying to make a reusable js module that I could use/load in different Blade templates.
So I created a file 'menu-btn-toggle.js' in 'resources/js/components/utilities'.
export class MenuBtnToggle
{
constructor() {
console.log('MenuBtnToggle');
}
}
I then created a 'utilities.js' file in 'resources/js/components'.
import './utilities/menu-btn-toggle';
I then updated the 'app.js' file in 'resources/js'
import './bootstrap';
import './components/utilities';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
So far, this seems to be working (?). Atleast, i think so. Vite is not giving me any errors so far (yay!)
But then I try to import the module in a blade template, but I can't get it to work.
So at the bottom of my blade template, I added this:
<script type="module">
import MenuBtnToggle from 'menu-btn-toggle';
new MenuBtnToggle();
</script>
But this gives me the following error:
Uncaught TypeError: Error resolving module specifier “menu-btn-toggle”. Relative module specifiers must start with “./”, “../” or “/”.
But when I add one of the examples, the error changes to:
Loading module from “[local_dev_url]/menu-btn-toggle” was blocked because of a disallowed MIME type (“text/html”).
as it isn't be able to find the module. It returns a 404.
Is it even possible do to want I want without a frontend framework? Or am I not seeing something obvious? I have experience with php, unfortunately not (enough) with Laravel and Vite.

I was stuck into almost same situation where we are not able to use import statement inside our blade files using Vite. We commonly get
Uncaught TypeError: Error resolving module specifier
“menu-btn-toggle”. Relative module specifiers must start with “./”,
“../” or “/”.
or We get 404 Blocked error nearly same as
Loading module from “[local_dev_url]/menu-btn-toggle” was blocked
because of a disallowed MIME type (“text/html”).
When importing external npm packages or modules, we need to put them in windows object just like you did above for Alpine
window.Alpine = Alpine;
But for your specific case problem you must do following
1)Inside menu-btn-toggle.js
export class MenuBtnToggle
{
constructor() {
console.log('MenuBtnToggle');
}
}
2)Inside utilities.js
import {MenuBtnToggle} from "./utilities/menu-btn-toggle";
window.MenuBtnToggle = MenuBtnToggle;
And then finally inside your app.js
import './components/utilities';
Now inside your .blade file, there is no need to import the MenuBtnToggle
instead just do it like
new MenuBtnToggle();
No need to use import MenuBtnToggle from 'menu-btn-toggle'; in blade.
Important thing is to import your app.js file properly inside .blade file through vite
#vite(['resources/css/app.css','resources/js/app.js'])
And it works. It has worked when reproducing same files/setup as yours.

Related

Uncaught SyntaxError: Cannot use import statement outside a module Vue 3 PWA Workbox

I am trying to convert my vue js app into a PWA. Following the workbox documentation in the following link:
https://developers.google.com/web/tools/workbox/modules/workbox-strategies
I have to import some modules
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
import { Queue } from 'workbox-background-sync';
After running npm run build, vue js automatically generates the following line of code which is at the top of service-worker.js file followed by the imports mentioned above:
importScripts("/precache-manifest.f6666fe9d8f679ee90db8a98ef900aa4.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
My app is fully functional without any errors, if I remove the imports, the service worker is registered successfully. When i add the imports I am getting this error:
Uncaught SyntaxError: Cannot use import statement outside a module
Error during service worker registration: TypeError: Failed to register a ServiceWorker for scope ('http://127.0.0.1:8887/') with script ('http://127.0.0.1:8887/service-worker.js'): ServiceWorker script evaluation failed
From my research I have learned that the scripts need to be bundled using webpack or a similar service.
https://developers.google.com/web/tools/workbox/guides/using-bundlers
However since I am using the CDN to importScripts, according to my understanding it should automatically bundle as stated in the following website:
https://developers.google.com/web/tools/workbox/modules/workbox-sw
It's an either-or thing: if you have full control over your build a bundling process, then following the "Using bundlers with Workbox" guide and using the ES module import {...} from '...' syntax, but not using workbox-sw, would work.
If you don't have full control over your build process (and it sounds like you don't), then you can use workbox-sw to load the rest of Workbox. Since you already have the importScripts('/path/to/workbox-sw.js') in your service worker, using statements like workbox.routing.registerRoute() or workbox.strategies.registerRoute() in your service worker, and not putting in any import {...} from '...' statements, should just work.

import module without nodejs - vanillaJS

I'm refreshing my old and low knowledge on VanillaJS using the latest best practices i found.
I recently did a tutorial on NodeJS doing API REST with ExpressJs and one with Socket IO.
Now I want to practice a little before going to REACTJS.
So I started a little project
I do one without NodeJs - just JS into HTML view - using Objects.
I want to use modules from Npm. I want to try Fakerjs but when i want to import it i have a 403.
The path is correct, no error.
So i'm wondering if it's possible without Nodejs to import modules when doing VanillaJs?
Am i doing it wrong ?
The structure of the project is :
js/
main.js
class/
node_modules/
index.html
Main.js:
'use strict'
//Importation of modules
import faker from '../node_modules/faker'
//Importation of Class Folder
import { Crypto } from "./class/crypto.class.js";
console.log(faker);
faker.locale = 'en_US';
I have this error in console:
GET http://crypto-market-js.local:8282/node_modules/faker/ net::ERR_ABORTED 403 (Forbidden)
If i write : import faker from 'faker' (like with node js but it's a require instead) i have this : Uncaught TypeError: Failed to resolve module specifier "faker". Relative references must start with either "/", "./", or "../".
If you could give me a hand on that plz :)
Trying to import with require is not supported without NodeJS, because require is a node-specific function. When trying to import modules into Vanilla JS, my recommendation is to first link to ths script with the <script> html tag, and then add another script with import faker from 'faker'
Hope that clarifies your issue.

"Uncaught SyntaxError: Cannot use import statement outside a module" When Importing ReactJS

Today I decided to try to learn React, but whenever I try to import the two modules below:
import React from "react"
import ReactDOM from "react-dom"
I get the error:
Uncaught SyntaxError: Cannot use import statement outside a module
Here's the steps I've taken to try to create my React program:
Install NodeJS
Add NodeJS to environmental variables
Create new folder for my program
Create HTML, CSS, and JS files in my folder
Why am I getting this error, and how can I fix it?
I assume this is your first time working with React? I see that you have installed NodeJs, which is great!
I recommend that you get started with a complete React app such as Create React App.
https://create-react-app.dev/
I am also new to react and using visual studio2022 to write the react code in MVC project. I created login page exactly same as https://github.com/narendra315/yt-210911-react-login-page/blob/master/src/LoginComponent2.js
and was getting same error as
Uncaught SyntaxError: Cannot use import statement outside a module
fixed it by removing the import as well as export line at the end. I replaced the export line with
ReactDOM.render(<LoginComponent />, document.getElementById('content'));
where LoginComponent is my class and content is id of my Index.cshtml page
This fixed my issue.
You need to add this to your package.json and it should work. If you are going to use es6 import statements you need to tell node you are using modules inside of your package.json like this.
"type": "module",

Creating a javascript module that imports and patch another

I am trying to write a JavaScript module that will be imported in the browser. This module should import and patch another which uses UMD (Universal Module Definition).
In this new module I do import 'old.js'; I get the following TypeError: root is undefined. What is the correct way to do it?

Error trying to import 'systemjs' to use import dynamically

I am trying to use SystemJS to import a module that lives on an external server. Having problems just getting started with importing systemjs so that I can use it in code.
import System from 'systemjs';
OR
import * as System from 'systemjs';
// System not found, error on line above trying to import systemjs as module.
System.import('https://test.com/modules/somemodule.js').then(module => {
// got the module
});
Neither work. This is all assuming its possible to use System.import(...) in code to import a module. Reading through the docs not really sure how to import systemjs.
Error:
Module not found: Error: Can't resolve 'systemjs'

Categories

Resources