How do I make my js file works for both ES6 modules and normal js?

Viewed 675

I have a js file looks like this. I want this file works for both

<script src="./foo.js"><script>

and

<script type="module" src="index.js"><script>


foo.js

const foo = () => console.log('Hello World!');

if (typeof module !== 'undefined') {
    module.exports = foo;
}

export default foo;

index.js

import foo from './foo.js';

foo();

But this doesn't work, it gives me an error while I'm using <script src="./foo.js"><script> syntax to import my foo.js.

Uncaught SyntaxError: Unexpected token 'export'

Is there a way to make my foo.js works for both of the situations?


Here is a repo contains these files on GitHub.

1 Answers

ES6 module doesn’t work on the file:// protocol, you need to use serve to run a server locally for testing.

And in your index-normal.html, you need to add type="module" and then import foo() in order to use foo() in the callback function.

<script type="module">
    import foo from './foo.js';

    window.addEventListener('load', function () {
        foo();
    });
</script>
Related