Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why JS cannot find the function in babel script?

Here’s my index file

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta content="IE=Edge" http-equiv="X-UA-Compatible">
    <meta name="description" content="test">
    <title>test</title>
</head>

<body>
    <!-- <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/fetch-polyfill@0.8.2/fetch.js"></script> -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script src="/app.js" type='text/babel'></script>
    
    
    <script type="text/javascript">
        fnc();
    </script>

</body>

</html>

And here’s app.js file

function fnc() {
    console.log('myname');
}

I wonder why console says:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught ReferenceError: fnc is not defined
    at (index):19
(anonymous) @ (index):19

If I change script type with text/javascript, it works without problem.
However, I need it to be babel script for tensorflow script to work in IE11.

Can anybody help me out?

>Solution :

In addition to @CertainPerformance‘s answer,

If you want to call the function fnc() directly, Then the type should be text/babel, Because it is defined in babel and transpiled. If you use text/javascript it will search for it in window object.

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="/app.js" type='text/babel'></script>

<script type="text/babel"> //<-- not text/javascript
    fnc(); // works fine
</script>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading