Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript/Knex: Cannot use import statement outside a module

I'm a newbie to TypeScript and currently using Knex to build a template table in our PostgreSQL database. On this file and others and am continually running in to this same issue with TypeScript, code is as follows:

import * as Knex from 'knex';


exports.up = async (knex: Knex): Promise<void> => {
    await knex.schema.raw(`
    CREATE TABLE test (
        test TEXT NOT NULL,
        tes2  INTEGER NOT NULL,
        PRIMARY KEY (key, website)
    ) 
`);
}


exports.down = async (knex: Knex): Promise<void> => {
    await knex.schema.dropTable('test');
}

and I get this error:

import * as Knex from 'knex';
^^^^^^

SyntaxError: Cannot use import statement outside a module

I have also tried these varients:

   import * as Knex = require('knex');
   import { * as Knex } from 'knex';
   const * = require('knex');
   const { * as Knex } = require('knex');

But I cannot find any solution online which seems to solve the problem.

Any help on this would be awesome.

like image 319
Maximoose Avatar asked Feb 07 '26 08:02

Maximoose


2 Answers

Tried alot of things and nothing helped, trying to change the type to module only made things worse. After all what was missing was ts-node:

yarn add ts-node -D

And you're done =]

like image 196
Marcos Capistrano dePaula Avatar answered Feb 09 '26 01:02

Marcos Capistrano dePaula


This error can occur if you setup knex without specifying you'll be using typescript.

Make sure you use the following command to initialize knex, if you're creating typescript migrations:

knex init -x ts
like image 43
Castrohenge Avatar answered Feb 09 '26 01:02

Castrohenge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!