Exportin/importing javascript modules - javascript

Nooby question:
I've got file main.js with module let myModule = {}, defined there inside $(document).ready(function(). And I have another file summary.js where I would like to use it. I declare them all in the head of html file:
<script src="js/main.js"></script>
<script src="js/summary.js"></script>
I would like to use myModule module in the summary.js file and extend it. So I would like to be able to define: myModule.summary = {}. For now I receive the error myModule is undefined even though all js files are uploaded correctly (I can see them in debugger in dev console of the browser). I expect I have to export the mdrx module somehow but export default mdrx at the end of main.js does not do the job. How to do it correctly? I read the documentation but it seems like structural problem as I couldn't figure that out. Can that be that the myModule is not loaded yet before loding summary.js? If so how to prevent that?

You can use the type attribute to achieve this:
<script src="js/main.js" type="module"></script>
Then you can import the module in other JavaScript files:
import yourModule from './main.js'

The problem was that the whole myModule was defined inside function() (called within document.ready event). Moving it outside that solved the problem.

Related

Laravel Vite Can't Use JS Functions Globally

I'm using Laravel with Vite. But I'm having a trouble. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
I have an app.js file looks like this:
import jQuery from 'jquery';
window.$ = jQuery;
import './bootstrap';
import './main.js';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
And I have a function like this in main.js:
function testFunction() {
alert('test');
}
I put Vite definitions to my layout blade like this:
#vite(['resources/css/app.css', 'resources/js/app.js'])
I have another page contains another JS file like this:
#extends('layouts.app')
#section('content')
#endsection
#section('scripts')
#vite(['resources/js/edit-note-page.js'])
#endsection
And in that JS file I want to use the function that I mentioned in the beginning like this:
testFunction();
But I'm getting an Uncaught ReferenceError: testFunction is not defined error in console. I couldn't figure it out. What is the correct way to do it?
I'm using Laravel with Vite. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
Each file is going to be wrapped to actually prevent what you are attempting to do, unless explicitly defined on the window object (notice how window.Alpine = Alpine; is set in your app.js). An alternative and more modern way is to use exports. Here is an example using your file structure.
main.js:
function testFunction() {
alert('test');
}
export default testFunction;
edit-note-page.js:
import testFunction from './path/to/file/name';
...code here
The path to the file in the import does not need the extension .js at the end.
Note: After this change, you no longer need import './main.js'; inside of app.js

Referencing vanilla js file in TypeScript getting file is not a module

I'm trying to import a file into TypeScript that's basically just a js file that you'd put into a tag. I've tried a few different things.
// global.d.ts
declare module 'myfile.js'
Inside of the react file:
// component.tsx
import { foo } from '../lib/myFile.js' // This is saying it is not a module
Inside of the js file, it looks like this a few times so not sure how I need to reference the file:
(function( something ) {
something.Foo = function (){}
}(window.something = window.something || {}));
Any thoughts on how I could use this file? Do I need to go through and declare typings for everything in it?
EDIT: I've added allowJS to my tsconfig but it still doesn't work.
You can only import what is exported from the file.
If your file contains only immediately invoked functions, or top level code, you only need to import the file itself like this:
import '../lib/myFile.js'
This is a little weird, however. I would suggest wrapping everything with a function and exporting then importing that function instead.

Importing JS function to another file

I'm trying to add an import to one of my JS files (both JS are in the same directory) but it seems to break with the following error:
"SyntaxError: import declarations may only appear at top level of a module"
<--HTML-->
click me
<---main_file.js--->
import { new_func } from "./new_file.js";
function run_my_func(){
...
}
<---new_file.js--->
export { new_func };
function new_func(){
....
}
I tried to read other questions on this topic but couldn't find a proper solution.
I've tried also changing the ahref to script type="module" but it didn't work either.
any suggestions?
EDIT:
So I managed to fix it, and it might not be the best practice but it works for my scenario as I want to use a specific function is several JS files -
in the HTML script that loads the function I want to export (new_file.js) I added type="module".
<script type="module" src="js/new_file.js"></script>
made new_func a global variable by adding it to window:
window.new_func = function() {
...
}
now I used new_func normally in every JS file that was imported after new_file

Understanding how to pass modules to index.js - relationship between js modules and main javascript

I am writing a javascript app and implementing three.js. To use this I use the script tag in my html file:
<script src="./scene.js" type="module"></script>
I have my main index.js file that contains all of the parameters and functions for my main index.html page. In this index.js I have an array of objects which I would like to pass to scene.js
I do not know how to achieve this. My understanding is that to export functions/parameters, the js file needs to be a module (declared in html using type="module"). If this is not declared as a module, I get the error 'unexpected token 'export''
If I make this a module though, I cannot reference functions in my html file that are triggered by buttons.
My index.html has my two scripts defined as this:
<script src="./index" ></script>
<script src="./scene.js" type="module"></script>
My index.js I want to export one array:
export var myArray = []
My three.js file contains the following first few lines:
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r127/build/three.module.js';
import { myArray } from './index.js';
I am confused how to continue. I cannot have everything in the one js file, as I could not import my three module

Call js function defined in a babel script from HTML

I am including my js file into my main html file like so
<script type="text/babel" src="js/scripts.js"></script>
Then I call one of my functions like so
<div class="allButton" id="completeAll" onclick="showAll('completeColumn');">Show All (...)</div>
the function looks like this
function showAll(column) {
$('div[id^='+column+']').removeClass('hide');
};
When I click the button(div) I get this error
Uncaught ReferenceError: showAll is not defined
I am using the text/babel as my script type because the file contains React JS stuff.
I have no idea why I simply cannot call my function. I am extremely new to ReactJS and Babel. (note: I am not using npm/gulp due to limitations)
Any help and/or advice would be appreciated
If you just define your function as follows you will be able to call it within the HTML.
window.showAll = function showAll(column) {
// your code here...
};
You have not exported your showAll function. When you transpile a JS/JSX file with Babel and bundle it to a scripts.js file (using Browserify or similar utilities), you must make sure to export your module (which tells your bundler to package it into your bundled file).
Your code should look like this:
var showAll = function(column) {
$('div[id^='+column+']').removeClass('hide');
};
module.exports = showAll;
This tells your bundler that your showAll method needs to be exported and available to other referenced namespaces.

Categories