Importing JS function to another file - javascript

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

Related

Problem with Include JavaScript from another JavaScript in the browser

I am importing in my main JS another JS from a CDN conditionally like this:
if (('standalone' in navigator) && (!navigator.standalone)) {
import('https://unpkg.com/pwacompat');
}
But I'd like to self-host it and include this JS file into my main JS file with JavaScript in the browser method. Like this:
pwacompact.js:
function pwacompact() {
console.log("pwacompact");
}
export { logpwacompact };
// here goes the js I want to import...
main.js:
// ... other functions preceding the conditional import statement, and then:
if (('standalone' in navigator) && (!navigator.standalone)) {
import { pwacompact } from "pwacompact.min.js";
logpwacompact();
}
The problem in main.js is that I want to place this import at the bottom of the script, but I can't because I get a Parse error: The import statement may only appear at the top level.
Please, how can I solve this? How can I include the second JS into the main JS and load it conditionally?
Thanks!

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.

Exportin/importing javascript modules

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.

Cannot use console.log() in a module

I'm trying to understand how to use modules in javascript.
But it seems that if I import a module, then I cannot log anything to console.
Here's my code:
index.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="js/scene.js" type="module"></script>
<script src="js/main.js" type="module"></script>
</body>
</html>
scene.js:
class Scene {
constructor() {
console.log("Scene created");
}
}
export default Scene;
main.js:
import { Scene } from './js/scene.js';
var scene = new Scene();
console.log("Hello World");
The Expected Result:
Scene created
Hello World
The Result I Get:
Nothing (No Result)
What is wrong with my code and how can I properly use a module?
I see 3 mistakes
in index.html the first script tag is useless.
import is relative to script file, not html.
Scene.js export a default value not a variable named Scene.
solutions:
import Scene from './scene.js';
or
remove default in Scene.js, and import {Scene} from './scene.js';
In your scenario, I believe that line 1 of main.js is throwing an error. In your index.html file, you're suggesting that you have a folder named js with both javascript modules in it; however, in the main.js file, you're suggesting that scene.js is at path js/js/scene.js.
You probably meant import { Scene } from './scene.js';.
You should open your browser's console to view any errors.
For example, if you are using Google Chrome, becoming familiar with the Chrome Devtools will be invaluable in allowing you to resolve bugs like this one by yourself in the future.
The Chrome Devtools console will allow you to view errors in your website, which will give you an immediate answer on what is wrong. In addition, setting breakpoints will allow you to step-through each line of code and trace the flow of executed lines of code and the value of variables at each point in time.
Learn more here: https://developers.google.com/web/tools/chrome-devtools/javascript

Can't figure out how to import modules in browser with javascript

This is a simple problem. I'm attempting to import modules from one javascript file to another, and then run it on Chrome. I'm using 2 javascript files and an html file, all in the same folder:
first js file (testfile1.js):
import {test} from 'testfile2.js';
test.func();
second js file (testfile2.js):
let f = function() {
console.log("TEST");
}
let test = {
func: f
};
export test;
The html file is plain, empty html file with a link to testfile1.js script in the header:
<script type="text/javascript" src="testfile1.js"></script>
Whenever I open the html file in chrome, I get the error:
testfile1.js:1 Uncaught SyntaxError: Unexpected token {
When I removed the brackets in the import statement, I get an unexpected identifier statement. Isn't this the proper way to import modules in the browser? Why is it not working at all?
Modules require type="module" not "text/javascript"
As per Jaromanda X's comment, you need to change the value of the type attribute of the <script> tag to "module" as import { test } from 'testfile2.js' is module code.
<script type="module" src="testfile1.js" />
What about dynamic import()
If you really don't feel like using type="module", any javascript file is allowed to use the dynamic import() syntax, even without type="module".
However, the dynamic import has a caveat, the function import() returns a promise, therefore, you are unable to use it synchronously. You must either await or .then a dynamic import to use the value it resolves to.
import('testfile2.js').then(({ test }) => {
// your code
});

Categories