#Using ESM Module with Nest.JS

4 messages · Page 1 of 1 (latest)

marsh radish
#

Hello guys im trying use @xenova/transformers as known transformers package by Hugging Face.

There is any way use esm module with nest?

javascript
import { Injectable, OnModuleInit } from '@nestjs/common';
import path from "path";
import { TextClassificationPipeline, pipeline } from '@xenova/transformers';


@Injectable()
export class ChatService implements OnModuleInit {

    textPipeline: TextClassificationPipeline;

    async onModuleInit() {
        this.textPipeline = await pipeline("sentiment-analysis");
    }

    async givePrompt(): Promise<string> {

        const generatedResponse = await this.textPipeline("I am happy");

        console.log(generatedResponse);
        return ""

    }
}

Error:

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/halit/Desktop/gpt-backend/node_modules/@xenova/transformers/src/transformers.js from /Users/halit/Desktop/gpt-backend/dist/chat/chat.service.js not supported.
Instead change the require of transformers.js in /Users/halit/Desktop/gpt-backend/dist/chat/chat.service.js to a dynamic import() which is available in all CommonJS modules.
    at /Users/halit/Desktop/gpt-backend/dist/chat/chat.service.js:13:59
    at async ChatService.onModuleInit (/Users/halit/Desktop/gpt-backend/dist/chat/chat.service.js:13:24)
``` g
marsh radish
#

Okay guys i figure out, but types is looking very bad (all of them any):

import { Injectable, OnModuleInit } from '@nestjs/common';

@Injectable()
export class ChatService implements OnModuleInit {
    pipeline;

    async onModuleInit() {
        const { pipeline } = await import('@xenova/transformers'); // Convert to commonJS module, its creep
        this.pipeline = pipeline;
    }

    async givePrompt(): Promise<string> {

        const textPipeline = await this.pipeline('sentiment-analysis');
        const generatedResponse = await textPipeline("I am happy")
        console.log({ generatedResponse });
        return ""

    }
}

Any advice for fixing types?

shy rose
#

one example on using a ESM-only package called delay:

import { Module, Inject } from '@nestjs/common';

const dynamicImport = async (packageName: string) =>
  new Function(`return import('${packageName}')`)();

@Module({
  providers: [
    {
      provide: 'package:delay',
      useFactory: () => dynamicImport('delay').then(p => p.default)
    }
  ]
})
export class AppModule {
  @Inject('package:delay')
  private readonly delay: typeof import('delay').default

  async onModuleInit() {
    console.time('>')
    await this.delay(1000)
    console.timeEnd('>')
  }
}

a bit uggly tho

brave windBOT
#
#3 Reputation of micalevisk 🇧🇷
Level

<@&918988965095297055>

Reputation

211

Next Level
181/Ꝏ  ____________________```