How to export variables to other javascript file - javascript

I want to use variables which is in main.js file in other js file and I tried everything ( exporting modules, declaring global variables) but nothing works and I have to do it because other js file is greatly dependent to those variables which are in main.js file.
Is there any other way to do it, if yes, please enlighten me.

Since you've stated that you're writing JavaScript code to be executed in web browsers, here's what your main.js file may look like (holding the variable importantVariable):
const importantVariable = 10;
Next, we have another JavaScript file, other.js (using the variable importantVariable):
console.log(importantVariable);
In the HTML document, where you're willing to use the scripts, include the main.js BEFORE the other.js file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="main.js"></script>
<script src="other.js"></script>
</body>
</html>
You should get "10" in the console, which indicates that the variable sharing of one file with other[s] worked successfully.
Explanation: A variable in the global scope should be accessible to all scripts loaded after it is declared.

We can use es modules in browsers.
index.html
<!DOCTYPE html>
<html>
<body>
<script type="module" src="./main.js"
</body>
</html
main.js
import { message } from "./other.js";
console.log(message)
other.js
export const message = "haha"
Note:
Due to the CORS policy, openning index.html directly will throw an error.
...has been blocked by CORS policy...
So you need to deploy them in an server.

Have you tried importing it into the receiving JavaScript file? This can sometimes be necessary as well as exporting it. Here's an example
In index.js:
export someVariable
In otherFIle.js: import { someVariable } from './index'

Related

My inline Javascript html is calling an external JS function, but the file is only running previous code. Why?

I created a Flask App using Pycharm.
I have an inline Javascript function internaltest() which is placed inside a html file. When I click a button, the function is supposed to call an external javascript function, and post an alert. For some reason, instead of running the current code in the Javascript file, it runs the previous code. (see below)
hom2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="/static/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="{{url_for('static', filename='test.js')}}"></script>
<script>
function internaltest(){
externaltest();
}
</script>
<button onclick="internaltest()">clickhere</button>
</body>
</html>
test.js (current version)
function externaltest() {
alert("This is supposed to be running");
}
test.js (previous version)
function externaltest() {
alert("This is NOT supposed to run");
}
I first ran test.js from hom2.html, which worked. Then I changed the alert from test.js and ran hom2.html again. Instead of alerting the new string, it alerts the one before I made the changes.
Directory:
app_code
static
test.js
templates
hom2.html
I would appreciate any help.

Import JS function in HTML

I have a JS file that exports some functions. I need one of those in the download attribute of the HTML body tag. How do I import the JavaScript function into the inline HTML?
I tried the following:
JS file
export function initPage() { ... }
HTML file
<script type="module" src="js/script.js"></script>
<body onload="initPage()">
But I get this error message:
Uncaught ReferenceError: initPage is not defined
I've found a Stackoverflow question but lost the URL to it. If someone knows which question I mean, please share the link and I'll delete this question
Thank you!
You could try following:
{...}
<body>
{...}
<!-- End of the body -->
<script type="module">
import {initPage} from '...';
document.addEventListener('DOMContentLoaded', function(event) {
initPage();
});
</script>
</body>
Basically the event listener DOMContentLoaded might be a modern way of solving your problem.
I've found a solution which is very easy, not quite exact that what I wanted but it works:
<script type="module">
import {initPage} from "./js/file.js";
document.querySelector("body").onload = function () { initPage(); } ;
</script>
Now the <script>-Tags with a src attribute aren't necessary anymore.
I did some tries and what seemed to work for me was to remove type="module" from the script tag and the export from the js function
Edit: What I meant was something like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/js/script.js"></script>
</head>
<body onload="initPage()">
</body>
</html>
and
function initPage() {
console.log('hupp');
}

Webpack, React & Babel, not rendering DOM

I finally after hours made my Webpack, React & Babel build setup, but when I try to just run a simple render Hello World it doesn't output anything in the DOM.
Here is my code.
var React = require('react');
var ReactDOM = require('react-dom');
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('content')
);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="bundle.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
And when I watch my bundle.js I can see it imports all the React & ReactDOM I need to run the render.
The test I'm running is from: https://facebook.github.io/react/docs/getting-started.html.
Getting this console error: Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
Your bundle.js file is being loaded before the DOM has had time to load. This means that it won't be able to find your <div id="content"> when you have asked for it.
Try putting the script loader before the end of the body.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<div id="content"></div>
<script src="bundle.js"></script>
</body>
</html>
When browsers find a <script> tag, they pause execution while they download the file. This means that your DOM has only partially rendered when your bundle.js script begins executing. So you would have essentially been passing undefined to the ReactDOM.render method.
If you have not had this issue in the past, perhaps you have been using the jQuery.ready event handler, which waits for the DOM to be loaded before executing.
bundle.js is executed when the content element isn't yet parsed an created. Just move your script element to the end of the markup.

Error using Angular.js

I've been doing an Angular.js course, and now that I finished it, I wanted to give it a try and do some tests.
I used the basic html file for beginning:
<html ng-app="app.js">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="plugins/angular-min-1.4.3.js"></script>
</head>
<body>
</body>
</html>
... which points to the simple angular app.js main module declaration:
var app = angular.module('app', []);
Nothing strange here, no? I tried making a few directives and so, but nothing worked. Then, I found this error, which appears as soon as I only have the above code. I guess it's not adding well the plugin or I'm not declaring well the app variable.
12:32:44.547 Error: [$injector:modulerr]
http://errors.angularjs.org/1.4.3/$injector/modulerr?p0=app.js&p1=%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.4.3%2F%24injector%2Fnomod%3Fp0%3Dapp.js%0AJ%2F%3C%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A6%3A416%0Ade%2F%3C%2F%3C%2F%3C%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A24%3A66%0Aa%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A23%3A109%0Ade%2F%3C%2F%3C%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A23%3A1%0Ag%2F%3C%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A37%3A381%0Am%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A7%3A320%0Ag%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A37%3A229%0Aeb%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A40%3A1%0AAc%2Fd%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A19%3A339%0AAc%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A20%3A151%0AZd%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A18%3A464%0A%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A289%3A428%0Aa%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A176%3A73%0AGf%2Fc%40http%3A%2F%2Flocalhost%2FAngularPruebas%2Fplugins%2Fangular-min-1.4.3.js%3A35%3A212%0A1
angular-min-1.4.3.js:6:415
Why does this happen?
You have an error in html.
Your app is app, not app.js.
<html ng-app="app">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="plugins/angular-min-1.4.3.js"></script>
</head>
<body></body>
</html>
Ok, I was being really silly not adding the app.js file. Now that I added it, ng-app="app" finds it properly.
On ng-app, you must say the name of the app, in this case it's "app" and not the file. I recommend you also not using ng-app on the HTML tag.

Issue in Calling functions in another JS file in ASP.Net MVC application

I am new to ASP.NET MVC. I have an asp .net MVC application. I have a view index.cshtml. I have two JS files:- Master.js and Child.js. All JS functions are defined in Master.js and those functions are used in Child.js file.
I am getting following error: Object doesn't support property or method 'method1'.
If I copy whole code of Master.js and place it above code of Child.js, then it works very fine in MVC application.
Both JS files are working fine with ASP.NET web forms application.
I tried to load master.js file in _layouts.cshtml and child.js index.cshtml. I was hoping that master.js will load before child.js.
index.cshtml:-
#section JavaScript
{
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js"></ script>
<script src="../Scripts/child.js" type="text/javascript"></s cript>
}
layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/Master.js")
#RenderSection("javascript", false)
</head>
<body>
#RenderBody()
</body>
</html>
Thanks in advance
Additional Information:
In Master.js: I am extending the method as follows:
$.fn.method1 = function()
{
//My Code
};
I child.js : I am using the method as follows:
$('#MyDiv').method1();
I came across following link:
Problems with Jquery function extend in MVC4
I normally wrap extension functions like so:
(function ($) {
$.fn.method1 = function() {
//My Code
};
})(jQuery);
This seems to be the recommended way to go, according to the documentation; it helps avoid conflicts on the $ object.
[...] To work well with other plugins, and still use
the jQuery $ alias, we need to put all of our code inside of an
Immediately Invoked Function Expression, and then pass the function
jQuery, and name the parameter $
If you're trying to load these scripts via the bundler, you need something like:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquerywithcustomscripts").Include(
"~/scripts/jquery-{version}.js",
"~/scripts/master.js",
"~/scripts/child.js"));
}
}
with this in your _Layout.cshtml:
Scripts.Render("~/bundles/jquerywithcustomscripts")
It looks to me that you are including your Master.js function before you include jQuery. When rendered, your header section would look like this when sent to the browser:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title</title>
<script type="text/javascript" src="/bundles/modernizr"></script>
<script type="text/javascript" src="/master.js"></script>
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/4.5.1/1/MicrosoftAjax.js"> </script>
<script src="../Scripts/child.js" type="text/javascript"></script>
</head>
If you're extending jQuery in master.js, you need to include jQuery before the master.js reference. The reason why it probably works when you copy all of the code from master.js to child.js is because by that point jQuery has been defined.

Categories

Resources