knex: Problem with ESM modules

Environment

Knex version: 0.21.4 OS: macOS Node: v14.4.0

 ➜  ./node_modules/.bin/knex --esm migrate:latest --knexfile knexfile.mjs
Requiring external module /Users/umarhansa/development/project/node_modules/interpret/mjs-stub
TypeError: Cannot read property 'get' of undefined

That error is referring to the start of my knex.mjs file which looks like this:

import config from 'config';
const environment = config.get('environment');

When I log the value of config, it’s undefined meaning something is broken with ESM via knex. This was working in 0.21.1

Also please see: https://github.com/knex/knex/issues/3882 - can you include more ESM related tests please? It will help catch these issues before users do, thanks. So far I’ve experienced quite a few issues already with ESM + knex. Totally appreciate it’s still a relatively ‘new’ thing.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 1
  • Comments: 22 (9 by maintainers)

Commits related to this issue

Most upvoted comments

Hey thanks for looking.

Just to clarify, I do have "type": "module" in my package.json.

I have tried 0.21.5-next1 as requested:

./node_modules/.bin/knex --esm migrate:latest --knexfile knexfile.js (esm flag, .js extension) produces the exact same error as mentioned from the start.

./node_modules/.bin/knex migrate:latest --knexfile knexfile.js (no esm flag, js extension) shows the error Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ...knexfile.js

./node_modules/.bin/knex --esm migrate:latest --knexfile knexfile.mjs (esm flag, .mjs extension): produces the exact same error as mentioned from the start.

./node_modules/.bin/knex migrate:latest --knexfile knexfile.mjs (no esm flag, .mjs extension): complains about my migration export function up(knex) { ^^^^^^ SyntaxError: Unexpected token 'export'


I have to go back to the old version 0.21.1. It’s the only way I can get it to work for me. Also note, I’m not doing anything ‘fancy’ or unique, it’s a very plain knexfile just importing a module. I haven’t looked at Knex’s implementation, but would highly recommend making standalone projects to test this all out with, and then using those projects as part of Knex.js tests, since these are probably common patterns many people will be using. Thanks again!