typicode / lowdb

Simple and fast JSON database
MIT License
21.35k stars 918 forks source link

Re-introduce main field to package.json #517

Closed shennan closed 2 years ago

shennan commented 2 years ago

I believe we should add "main" field to the package.json for this repository. This will also need to be done for the dependency "steno" which is in a PR here. The version in both this and steno's PR have been bumped as a patch, and this PR now references that patch of steno.

Why

Aside from the fact that nodejs.org advises to do so here...

it is advisable to define both "exports" and "main" in the package’s package.json

I'm also having trouble importing LowDB in a common project: a Create React App project. I presume the real problem is with Create React App's usage of Webpack 5, and it seemingly ignoring (or not properly implementing) the "exports" field in a module's package.json.

Recreating the issue is easy...

1) Create a CRA:

$ yarn create react-app my-app --template typescript

2) Navigate to project and install LowDB

$ cd my-app && yarn add lowdb

3) Import LowDB in some file, e.g src/index.ts:

import { Low } from 'lowdb'

console.log(Low)

4) Try and build/run:

$ yarn build

Command fails with:

Cannot find module: 'lowdb'. Make sure this package is installed.

The reason is that Webpack doesn't know how to find the package when it is bundling everything together. Running yarn list lowdb is a false-positive.

Testing the fix...

Simply find lowdb in the node_modules of the my-app CRA that you've just created and add "main": "./lib/index.js". You will also need to do the same with steno.

Then run yarn build and all is well...

Win win

I think this is a pretty straight forward addition and will probably help a lot of people out who are using Webpack to bundle.

There is a hack which is to use LowDB by importing the lib subdirectory (import { Low } from 'lowdb/lib), but this isn't sufficient when you're bundling other modules that do have the correct import syntax and a good bundler. So a big monorepo project suffers. So I think it's just easier/safer to include a "main" field in package.json.

Until this is resolved I will have to use a forked version of this library, and steno, which is a shame.

typicode commented 2 years ago

Hi @shennan,

Thank you for the PR and detailed explanation :)

For maintainability and simplicity, I'd rather stick to pure ESM package as described here: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

There seems to have been progress https://github.com/facebook/create-react-app/issues/10892 so hopefully it should be fixed (or it's already) in Create React App.

Thanks again for the PR and sorry for the delay.