0

When using the commonjs I used to import custom modules like this:-

const date = require(__dirname + "/date.js");

after switching to es module type I can no longer use the __dirname without creating one manually

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

import date from __dirname + "/date.js"

When I use this it shows me "unexpected identifier __dirname" on the import line.

date.js is in the same level of directory as this code file is in.

How do I import custom js module using es module syntax? Please help

Thank you

G Ajeet
  • 27
  • 5
  • Actually, I just found it's a duplicate. Does this answer your question? [How to perform a “variable” ES6 import?](https://stackoverflow.com/questions/29168433/how-to-perform-a-variable-es6-import) – Sebastian Kaczmarek Aug 31 '23 at 14:07
  • Just use relative paths instead of absolutes. – Marc Aug 31 '23 at 14:08

1 Answers1

1

Since the date.js file is in the same directory, you can use relative path:

import date from "./date.js"
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38