I have a simple web page made up of vanilla html, css and js files.
I’d like to be able to use the import { moment } from "moment"
syntax in my js files but when I add npm to my proejct, install moment wiht npm install
and use that syntax when I run my app using live-server I get an error:
Uncaught TypeError: Failed to resolve module specifier "moment". Relative references must start with either "/", "./", or "../".
2
Answers
The error you’re seeing is because the
import
syntax you’re trying to use is part of ES6 modules, which is not supported in all browsers and environments. When you’re working with a simple web page and not using a build tool like Webpack or Babel, you’ll need to include Moment.js through a<script>
tag in your HTML file.Here’s how you can do it:
You can include either of these in the
<head>
section of your HTML file.import
statement. Here’s an example:In this example, when you click the "Get Today!" button, it will show an alert with the current date and time, formatted with Moment.js.
If you want to use ES6
import
syntax, you would need to set up a build process with a tool like Webpack or Babel, or use a server-side environment like Node.jsYes, it’s possible. Browsers support native ES6 modules for more than 6 years. Here is an example configuration for Express, but it should work with all serious web servers.
index.html
:app.js
:index.js
:package.json
:I’ve used an import map to allow
import moment from 'moment';
without relative paths. You have to configure your web server to point to the Moment JavaScript code.If the web server doesn’t support a rewrite (as I used for Moment), you have to use the full path in the import map.
Here you can find out more about native ES6 modules: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules