knex / knex

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.
https://knexjs.org/
MIT License
19.24k stars 2.12k forks source link

Add 'cjs' to list of Seeder.js extensions to support Node "type": "Module" projects #4381

Open adamlove01 opened 3 years ago

adamlove01 commented 3 years ago

Environment

Knex version: 0.21.17 Database + version: postgres (PostgreSQL) 11.5 OS: MacOS Big Sur 11.2.3 NodeJS: v14.15.1

Bug

I am running NodeJS with ES modules enabled ("type": "module") and with Knex running with .cjs extension:

knexfile.cjs knex.cjs

Migration files and seed file also have .cjs extension: migrations ↳ articleTable.cjs ↳ userTable.cjs seeds ↳ articleTable.cjs

I can run migrations like this: npx knex migrate:latest --knexfile knexfile.cjs

This works normally.

Error

But when I run the seed like this: npx knex seed:run --knexfile knexfile.cjs

I receive error "No seed files exist"

Solution

I discovered the problem, which is in the Seeder.js file's setConfig(config) {} function:

  setConfig(config) {
    return extend(
      {
        extension: 'js',
        directory: './seeds',
        loadExtensions: [
          '.co',
          '.coffee',
          '.eg',
          '.iced',
          '.js',
          '.litcoffee',
          '.ls',
          '.ts',
        ],
        timestampFilenamePrefix: false,
        sortDirsSeparately: false,
        recursive: false,
      },
      this.config || {},
      config
    );
  }

If I add '.cjs' to the loadExtensions array, my seed file runs normally:

  setConfig(config) {
    return extend(
      {
        extension: 'js',
        directory: './seeds',
        loadExtensions: [
          '.co',
          '.coffee',
          '.eg',
          '.iced',
          '.js',
          '.litcoffee',
          '.ls',
          '.ts',
          '.cjs',
        ],
        timestampFilenamePrefix: false,
        sortDirsSeparately: false,
        recursive: false,
      },
      this.config || {},
      config
    );
  }

Proposal

I propose adding '.cjs' to the list of extensions to support using Knex in Node projects with "type": "module" enabled while running Knex in CommonJS mode.

kibertoad commented 3 years ago

@adamlove01 Could you please send a PR for this?

adamlove01 commented 3 years ago

Sure!

adamlove01 commented 3 years ago

https://github.com/knex/knex/pull/4382