Reputation: 75
A newbie here trying to understand how module.export vs export works.
When I use export { arr } and import { arr } from '../js/export.js'; everything works just fine. So that I could implement and use html to print the array onto the browser.
But using module.export does not work in the same way and I could not find any explanation that explains in a way that a node.js beginner can understand. Just to show exactly what I am trying to implement I will post the code I used for module.export , js and html to make it clear whats happening.
to recap I used export{} and import{} and everything works perfectly without any problems. That I understood perfectly but the problem will arise later when implementing more complex code and at that point I personally would prefer to use module.exports because it makes writing complex stuff much easier at least for my level of understanding. But I cant even understand how to get the array and print it. I used console.log() to test if the array can be printed from the imnporting file and it actually printed the array to the console with no problems. Thta means the problem lays with the browser and js file importing the file and thats where I am stuck as to how exactly to get the browser to print the array
//js model
module.exports = function somefunction() {
this.arrayss = function () {
var arr = ["example1", "example2", "example3"];
return arr;
};
};
// js file to import model
var fetch = require('../c');
var c = new fetch();
var arr = c.arrayss
function buildProducts(parent, array) {
var html = "";
array.forEach(function (i) {
//Set Our Itemp template
let itemTemplate = `
<li>
<div>item: ${i}</div>
</li>`;
//update the html
html += itemTemplate
});
//Update the parent once
parent.innerHTML += html;
}
buildProducts(document.getElementById("jj"), arr);
<html>
<head>
</head>
<body>
<div id="jj"></div>
<script type="module" src="/js/importfile.js"></script>
</body>
</html>
Upvotes: -3
Views: 122
Reputation: 944473
There are a number of different module formats for JavaScript, but the two most common ones in 2023 are CommonJS modules and ECMAScript modules.
Node.js has native support for both and recognises which module format is being used based on the type
specified in package.json and the file extension.
Web browsers (where you are running your code) only support ECMAScript modules natively.
import
and export
are the syntax used by ECMAScript modules.
require()
and module.exports
are used by CommonJS (which aren't natively supported by browsers).
Upvotes: 1