Reputation: 283
I am currently looking into converting some of my personal libraries into the module syntax for a project. This project is not using a framework, like Node.js or React. I would probably be using some of them in module syntax, and others not.
Say I have an object CookiePicker
. CookiePicker
was not written as a module, so it does not export any functions. CookiePicker
does import an object, DOMFactory
, to offload some of the work. When including CookiePicker.js
, which only contains object/function definitions, in the HTML, it seems I have to use type="module"
Later in the HTML, I open a script tag to actually use the object defined in CookiePicker.js
. But, I then get an error saying that my object is not defined. If I add type="module"
to this script tag, the code executes as expected, after I import the CookiePicker
object.
Is it not possible to chain module syntax with plain JS syntax?
/js/modules/DOMFactory.mjs
export default function DOMFactory()
{
...
}
./CookiePicker.js
import DOMFactory from '/js/Modules/DOMFactory.mjs';
function CookiePicker(arg1, arg2)
{
...
}
CookiePicker.prototype.init= function()
{
...
}
./CookiePicker.html
<html>
...
<script type="module" src="CookiePicker.js"></script>
...
<!-- ReferenceError
<script>
var s = new CookiePicker('selector', '');
s.init();
</script>
-->
<!-- Works once I add an export to the CookiePicker function -->
<script type="module">
import CookiePicker from './CookiePicker.js'
var s = new CookiePicker('selector', '');
s.init();
</script>
</html>
Upvotes: 1
Views: 1931
Reputation: 370989
Say I have an object CookiePicker. CookiePicker was not written as a module, so it does not export any functions.
It uses import
, so it has been written as a module - only modules can use the import
(or export
) keyword. So, you're right when you say:
When including CookiePicker.js, which only contains object/function definitions, in the HTML, it seems I have to use type="module"
Is it not possible to chain module syntax with plain JS syntax?
Not easily. Modules generally run asynchronously, and they purposefully do not pollute the global object, so hooking into them from an external non-module script isn't all that natural.
While you could do something like add an event listener for the event when the module fully loads, and have the outermost module trigger that listener, it's ugly and isn't really the way to use modules. The right way to do this would be to, since modules are involved, make everything a module, per your
<!-- Works once I add an export to the CookiePicker function -->
Doing that is just fine, and would probably be the best way to do it.
Upvotes: 2