node.jstypescriptimporthapilokijs

TypeError: Loki is not a constructor


I don't seem to be able to figure out why this is not working

My Hapi.js index.ts looks like this:

import { Server, Request, ResponseToolkit } from '@hapi/hapi';
import * as Loki from 'lokijs';

...

const db = new Loki(`${UPLOAD_PATH}/${DB_NAME}`, { persistenceMethod: 'fs' });

which is pretty straight forward, and is taken from a well known example

The scripts in my package.json look like this:

"scripts": {
"prestart": "tsc",
"start": "node dist/index.js",
...

which compile into dist/index.js When I run start, I get the following error:

TypeError: Loki is not a constructor

I have tried all sort of things, but I guess I am missing the point, I'd be grateful if someone could please help me. Loki is not a constructor, I get that, but how can I instantiate a new Loki(), and how come the same exact thing works elsewhere?

Thank you for your help!


Solution

  • You can do either of the following:

    import * as Loki from 'lokijs';
    const db = new Loki.default(`${UPLOAD_PATH}/${DB_NAME}`, { persistenceMethod: 'fs' });
    // For me, I don't like this way. It looks bad.
    

    or

    import Loki from 'lokijs';
    const db = new Loki(`${UPLOAD_PATH}/${DB_NAME}`, { persistenceMethod: 'fs' });
    

    Looking inside lokijs, the class seems to be exported as module.exports = factory(), equivalent to export default factory(), so the class is exported as default. Here is a helpful question to undestand what I mean: ES6: "import * as alias" vs "import alias"