Skip to content

Commit 5b53a66

Browse files
authored
Improve ESM import support (knex#4350)
1 parent 4ff3868 commit 5b53a66

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

README.md

+30
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,33 @@ try {
116116
// error handling
117117
}
118118
```
119+
120+
## Usage as ESM module
121+
122+
If you are launching your Node application with `--experimental-modules`, `knex.mjs` should be picked up automatically and named ESM import should work out-of-the-box.
123+
Otherwise, if you want to use named imports, you'll have to import knex like this:
124+
```js
125+
import { knex } from 'knex/knex.mjs'
126+
```
127+
128+
You can also just do the default import:
129+
```js
130+
import knex from 'knex'
131+
```
132+
133+
If you are not using TypeScript and would like the IntelliSense of your IDE to work correctly, it is recommended to set the type explicitly:
134+
```js
135+
/**
136+
* @type {Knex}
137+
*/
138+
const database = knex({
139+
client: 'mysql',
140+
connection: {
141+
host : '127.0.0.1',
142+
user : 'your_database_user',
143+
password : 'your_database_password',
144+
database : 'myapp_test'
145+
}
146+
});
147+
database.migrate.latest();
148+
```

knex.mjs

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Knex.js
2+
// --------------
3+
// (c) 2013-present Tim Griesser
4+
// Knex may be freely distributed under the MIT license.
5+
// For details and documentation:
6+
// http://knexjs.org
7+
8+
import knex from './lib/index.js';
9+
10+
export { knex }
11+
export default knex

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "knex",
33
"version": "0.95.1",
44
"description": "A batteries-included SQL query & schema builder for Postgres, MySQL and SQLite3 and the Browser",
5-
"main": "knex.js",
5+
"main": "knex",
66
"types": "types/index.d.ts",
77
"engines": {
88
"node": ">=10"

0 commit comments

Comments
 (0)