JavaScript/Node js import and export module(Using exported node Js module in JavaScript file) - javascript

I am trying to export node js modules to use in JavaScript. This is what I have done.
-Installed esm in node.
in my node file I did like this:
require = require("esm")(module/*, options*/);
export function Myjs(name, surname){console.log(name, surname)};
This does not give error.
In my js file I did:
1- import { Myjs } from '/javascripts/sockets/bases.js'; This gives error as "Uncaught SyntaxError: Cannot use import statement outside a module". I have been reading topics regarding this error, and it suggests that I should include "type: module" while including the file. But I do not include node js files as scripts on html.??
2- I try to import dynamically like this:
import('/javascripts/sockets/bases.js')
.then((module) => {
module.Myjs("bola", "carro");
});
This gives error if detects require() in the file and it gives error "require is not defined" or any node js module that js does not recognize.??
What I'm trying to achieve is: Based on an event on js file trigger the function (Myjs()) I'm trying to import. How could achieve this? I tried babel and I wasn't successful. Thanks

Related

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

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.

How to import mongoose-encryption instead of using "require"

I am using "type:" "module" in my package.json file and use "import" statements for all node packages rather than the require('packageName') syntax. But when I try to import mongoose-encryption like this:
import mongoose-encryption from 'mongoose-encryption';
...then, VS Code throws an error: 'import ... =' can only be used in TypeScript files. (ts 6133).
Mongoose-encryption is the only package giving me this error.
Help?

Uncaught SyntaxError: Cannot use import statement outside a module - Cordova

I am simply trying to access my common application variable/function from main.js file. using ES6- Import Export.
export var APP_NAME= "MyPOC"; - File main.js
Importing now in other javascript file- home.js,
import * as mainparams from './main.js';
console.log("variable_name:"+ mainparams.APP_NAME);
OR
import {APP_NAME} from './main.js';
console.log("variable_name:"+ APP_NAME);
Error: Uncaught SyntaxError: Cannot use import statement outside a module
The same thing is working while I am importing in my HTML page - index.html
<script type="module">
import {APP_NAME} from './js/main.js';
console.log("variable_name: "+ APP_NAME);
</script>
Result - Print in console - variable_name: MyPOC
What I did to fix the issue:
I checked the js file path, both js are in the same folder
Cross-check the cordova-plugin-whitelist package installed already
I tried to add "type" : "module" in package.json - Show me issue on terminal can't support ES6
Added <script type="module" src="main.js"></script> - Result: "unexpected token <"
None of the above action items working for me. I just want to normalize my code in different Javascript files for better code readability.
Using: HTML, CSS. JS, JQuery, Cordova, Phonegap Platform: Android, Browser
ES6- Java Script Import-Export
Cordova WhileList Plugin
Add module in package.json file or use module directly
Please help me out and thanks for your time to understand my issue.

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.

Post TypeScript Compilation: Uncaught SyntaxError: Unexpected token {

Scenario
Whenever I run my application from index.html, referencing the main.js file, which has been compiled from Typescript using es6 as the target and ESNext as the module, I get this error within the browser:
Error
main.js:3 Uncaught SyntaxError: Unexpected token {
Main.ts
/// IMPORTS
//////////////////////////////////////////////////////////////////////
import { Player } from './classes/Player' <= Error Here!
import { printTable } from './helpers/Helpers'
/// MAIN COMMANDS
//////////////////////////////////////////////////////////////////////
let p1 = new Player('Bob', 'Hunter', 1, 10);
printTable(p1);
Concept
I appear to be importing my code improperly, and (for whatever reason) don't know why or can't figure it out. Everywhere I look, this is indicated as the method of importing exported code, classes, etc... When all code exists within a single file, all classes, interfaces, helpers, etc..., everything converts and runs dandy, except when I want to compartmentalize my code, and handle it this way.
Any guidance would surely be appreciate.
Cheers and thanks in advance!
Source Code
...and ESNext as the module, I get this error within the browser:
main.js:3 Uncaught SyntaxError: Unexpected token {
Your error here is that you are trying to use ES6 import syntax in a traditional script (<script src="index.js"></script>). Using ES6 import and export only works with modules, used in the browser with <script type="module" src="whatever"></script>.
Have you looked into using Webpack? It can automatically compile your TypeScript files into one JavaScript bundle that you can load into your HTML file with a single script tag.
For you to import in this way you are using, you must export the class reference directly, without being inside an object.
Examples:
(correct) export Player;
(wrong) export { Player }

Categories

Resources