Absolutely, it is indeed possible. Browser support for native ES6 modules has been around for over 6 years now. Below is an example setup for Express, but this should be compatible with any major web server.
index.html
:
<!DOCTYPE html>
<html>
<head>
<script type="importmap">
{
"imports": {
"moment": "/moment"
}
}
</script>
<script type="module" src="/app.js"></script>
</head>
<body>
<h1>Moment</h1>
<div></div>
</body>
</html>
app.js
:
import moment from 'moment';
let x = new moment();
document.querySelector('div').textContent = x;
index.js
:
import express from 'express';
const app = express();
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/app.js', (req, res) => {
res.set('Content-Type', 'application/javascript');
res.sendFile(__dirname + '/app.js');
});
app.get('/moment', (req, res) => {
res.set('Content-Type', 'application/javascript');
res.sendFile(__dirname + '/node_modules/moment/dist/moment.js');
});
app.listen(8080, () => {
console.log('Server running...');
});
package.json
:
{
"name": "example",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.18.2",
"moment": "^2.29.4"
},
"type": "module",
"devDependencies": {
"@types/express": "^4.17.21"
}
}
An import map was utilized to enable import moment from 'moment';
without using relative paths. Your web server must be configured to direct to the Moment JavaScript code.
If your web server does not support a rewrite (like I did for Moment), you will need to use the full path in the import map.
To delve deeper into native ES6 modules, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules