Skip to content
Advertisement

How can I use import and export with this simple code?

I want to use the doAlert function in the index.js file. Now, how do I use import and export in this situation?

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

//index.js
/*'index.js' is an empty file.*/

//doAlert.js
function doAlert() {
    alert('Hello');
}

Advertisement

Answer

/* index.html */
<script type="module" src="index.js"></script>
<script type="module" src="doAlert.js"></script>

/* doAlert.js */
export function doAlert() {
    alert('Hello');
}

/* index.js */
import { doAlert } from './doAlert.js';
// use it
doAlert();

More info on JS modules: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement