In my ASP.Net Core MVC Application I have separate .js files for few pages, They contain normal validation and client side logic.
I have to put few method in a common util.js file and this file methods will be shared among another js files.
but I am not able to add the reference of this util.js into other external js files.
I have tried few approaches as
For example My util.js
export function ShowAlert(val) {
alert(val);
}
And than in another js file (MyApp.js) with import statement
import { ShowAlert } from './util'
function Info() {
var F = document.getElementsByName('txtFName')[0].value
var L = document.getElementsByName('txtLName')[0].value
if (F.length > 0 && L.length > 0)
ShowAlert(F + ' ' + L)
else
ShowAlert('Fields Required');
}
But it give error in import statement line
Unexpected token {
Than I tried babel tool to get browser compatible js, which is
//import { ShowAlert } from './util'
var _util = require('./util');
function Info() {
var F = document.getElementsByName('txtFName')[0].value
var L = document.getElementsByName('txtLName')[0].value
if (F.length > 0 && L.length > 0)
_util.ShowAlert(F + ' ' + L)
else
_util.ShowAlert('Fields Required');
}
Now it says require is not defined , so after searching few post on internet I found a solution and included require.js before MyApp.js
<script src="./require.js" type="text/javascript"></script>
<script src="./MyApp.js" type="text/javascript"></script>
But still the error is
Module name "util" has not been loaded yet for context: _. Use require([])
How can I have reference of one js file into another and why import is giving error here?
Update 1
Util.js
export default function ShowAlert(val) {
alert(val);}
MyApp.js
import { ShowAlert } from './util';
//var _util = require('./util');
function Info() {
var F = document.getElementsByName('txtFName')[0].value
var L = document.getElementsByName('txtLName')[0].value
if (F.length > 0 && L.length > 0)
ShowAlert(F + ' ' + L)
else
ShowAlert('Fields Required');
}