javascriptmime-typesdate-fns

Failed to load DATE-FNS


I'm trying to use DATE-FNS in a project with HTML and JavaScript, but the module is not working.

I'm using VS Code with the Liver Server extension.

My package.json:

{
  "name": "Project1",
  "version": "1.0.0",
  "dependencies": {
    "date-fns": "^2.29.3"  
  }
}

My HTML <head>:

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ToDo List</title>
  <link rel="stylesheet" href="styles.css">
  <script type="module"  src="Ui.js" defer></script>
  <script src="https://kit.fontawesome.com/efbd7c5f89.js" crossorigin="anonymous"></script>
</head>

When I call it in the script using this:

import { isToday, isThisWeek } from 'date-fns';

I get this error:

Uncaught TypeError: Failed to resolve module specifier "date-fns". Relative references must start with either "/", "./", or "../".

So I tried this:

import { isToday, isThisWeek } from './node_modules/date-fns';

but got this other error:

:5500/node_modules/date-fns/:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.


Solution

  • Try to import the ESM (ECMAScript modules) instead:

    import { isThisWeek, isToday } from "./node_modules/date-fns/esm/index.js";
    
    console.log("Today?", isToday(new Date()));        // true
    console.log("This Week?", isThisWeek(new Date())); // true
    

    Update: As of version 4.x, it looks like the import path for the ESM entry point is at the top-level:

    import { isThisWeek, isToday } from "./node_modules/date-fns/index.js";