jprichardson / node-fs-extra

Node.js: extra methods for the fs object like copy(), remove(), mkdirs()
MIT License
9.44k stars 776 forks source link

feat: support for esm named imports #986

Closed rxliuli closed 1 year ago

rxliuli commented 1 year ago

motivation

There are still problems with esm support at present, and named imports are not really available. For example, the following code will report an error when using the latest version of fs-extra

import { readdir } from 'fs-extra'
import fsExtra from 'fs-extra'
import { fileURLToPath } from 'url'
import path from 'path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
console.log(await readdir(__dirname))
console.log(await fsExtra.readdir(__dirname))

This PR addresses the following issues

For specific test methods, see: https://github.com/rxliuli/fs-extra-demo

RyanZim commented 1 year ago

This approach doesn't work for a couple of reasons:

For more details, see discussion on https://github.com/jprichardson/node-fs-extra/issues/746 & https://github.com/jprichardson/node-fs-extra/pull/854

rxliuli commented 1 year ago

This approach doesn't work for a couple of reasons:

  • fs.lchown is not available on some Linuxes
  • This doesn't allow us to export functions that are only available in some Node.js versions (not the case now, but has been in the past and likely will be in the future).

For more details, see discussion on #746 & #854

What I don't understand is why the export interface of its cjs version is different from that of esm version. In cjs, all the methods of fs itself can be used, but in esm export, it is not included. I understand that fs may have different exports between nodejs versions, while cjs always forwards and exposes all, and esm must be explicitly specified, but this can be solved by version, for example, different nodejs versions are required for different major versions. Speaking of ts support, if you do use another export point fs-extra/esm, even if the types are fixed, this can easily be mis-imported, because you have to take care to avoid importing from fs-extra, which can be annoying

RyanZim commented 1 year ago

this can be solved by version, for example, different nodejs versions are required for different major versions.

It's not practical to manage multiple major version release lines for different Node versions. This also still doesn't solve the obstacle with fs.lchown.

lvjiaxuan commented 6 months ago

Feel sad for this.