Consider a simple "module" such as:
function doSomething() {
alert("I am doing something");
}
export { doSomething };
Say it is in a file called doSomething.js
(or doSomething.mjs
if you prefer) and this file name has been entered in the script
array in angular.json
.
In the <head>
section of index.html you have
<script type="module">
import { doSomething } from "/doSomething.js"; // or /.mjs
doSomething();
</script>
If doSomething.js were a plain javascript file, (with no export
statement), all would be fine, but angular throws an error when encountering the export
statement, so you can’t really use modules (like this), especially not if they are going to import additional modules. Using .mjs instead of .js makes no difference — angular wants plain js, not a module. What am I missing? How does one load a module here?
2
Answers
I get it to work this way:
(1) Remove the module entry from
angular.json
;(2) Add
doSomething.js
toassets
folder to make it available;(3) Include the module to
index.html
file withinhead
tagNow the alert are shown and no error are thrown on console.
ps.: Tested on Angular 15
In an Angular application, importing and using ES modules directly in the
index.html
file is not supported. Angular uses its own build system and module loader to bundle and load JavaScript modules within the context of the Angular application.To use your
doSomething.js
module in an Angular application, you should follow the Angular module system and import the module within your Angular components or services instead of directly in theindex.html
file. Here’s how you can do it:Create a TypeScript module:
do-something.ts
, in your Angular project.doSomething
function inside this module file.doSomething
function as part of the module.Import the module in a component or service:
doSomething
function.doSomething
function from thedo-something
module file.Use the component or service in your application:
By following this approach, your modules will be properly bundled and managed within the Angular application. The module system provided by Angular enables better code organization, dependency management, and allows you to take advantage of TypeScript features.
It’s important to note that importing modules directly in the
index.html
file is not the recommended approach in Angular applications. Theindex.html
file is mainly used as the entry point for the Angular application, and the module loading and code execution should happen within the Angular context using Angular components, services, and modules.