ERROR: The use of @xenova/transformers for importing requires ESM

When working with my Node.js application, I usually start by importing the necessary modules like this:

import { AutoModel, AutoTokenizer } from '@xenova/transformers';

Afterwards, I utilize them in my code as shown below:

const tokenizer = await AutoTokenizer.from_pretrained('bert-base-uncased');

However, upon running my script, I encounter the following error message:

> node --experimental-modules lib/index.js

No storage option exists to persist the session, which may result in unexpected behavior when using auth.
        If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.
Starting script...
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/me/Projects/node_modules/@xenova/transformers/src/transformers.js from /home/me/Projects/lib/pinecone/utils.js not supported.
Instead change the require of transformers.js in /home/me/Projects/lib/pinecone/utils.js to a dynamic import() which is available in all CommonJS modules.
    at /home/me/Projects/lib/pinecone/utils.js:34:81
    at async syncProfilesOnPinecone (/home/me/Projects//lib/pinecone/utils.js:34:33)
    at async main (/home/me/Projects/lib/index.js:9:5) {
  code: 'ERR_REQUIRE_ESM'
}

If you're unsure about how to address this issue, here are some suggestions:

Answer №1

Greetings from the creator of Transformers.js!

The issue you are facing is not unique to transformers.js and is related to your node resolution settings in tsconfig.json. By default, all import statements get converted to require during compilation.

To resolve this, you can do the following:

TransformersApi = Function('return import("@xenova/transformers")')();
const { pipeline } = await TransformersApi;

This approach essentially postpones the import until after compilation. For more details, refer to this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in JavaScript: A surprise anonymous System.register call occurred

Within Visual Studio 2015, there exists a TypeScript project featuring two distinct TypeScript files: foo.ts export class Foo { bar(): string { return "hello"; } } app.ts /// <reference path="foo.ts"/> import {Foo} from './f ...

A node module designed to efficiently convert multiple TIFF images into a single multipage TIFF document

Looking to combine several tiff images into a single file using nodejs/javascript. Is there a method to create a single tiff file with multiple pages from separate tiff images in nodejs? Can we convert a multi-page pdf into one tiff image using nodejs? ...

Having trouble connecting to the online redis database

I am currently working on establishing a connection to my online redis database. const redis = require('redis'); const client = redis.createClient({ password: '<password>', socket: { host: <host> port: <p ...

Switching the Checkbox Data Binding Feature in Angular

I am looking to send a value based on a toggle switch checkbox selection between Hourly or Salary. How can I incorporate this into the form below? html <div class="row"> <div class="col-sm-6"> <div cl ...

Deleting a file using Node.js within an active script involves fully eliminating the file from

I am currently running a Node.js script in a continuous loop using while (true), which monitors specific directories for files and deletes them using the unlink API: fs.unlinkSync(path); These files are not generated by the Node process itself. According ...

Tips for incorporating external routes into the routes index file

I am currently dealing with a users.js and an index.js file. users.js const express = require('express'); const router = express.Router(); const {catchErrors} = require('../handlers/errorHandlers'); const authController = require(&ap ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...

The body of the POST request appears to be void of any

Whenever I make a request using curl or hurl, an issue arises. Despite req.headers['content-length'] showing the correct length and req.headers['content-type'] being accurate, req.body returns as {}. Below is the Hurl test: POST http:/ ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

Guide to authenticating Cashfree gateway's webhook signature using JavaScript

I have integrated the Cashfree payments gateway successfully. However, I am unsure how to verify the signature of webhooks. https://i.stack.imgur.com/TxdTx.png This is their recommended approach. Could someone guide me on writing JavaScript code for this ...

Tips for executing a SOAP request using NodeJs

Despite my efforts in researching various blogs, tutorials, and videos, I still can't find a clear answer on how to execute a RESTful request. For example, in NodeJs, you would code the request, hit the route (https://localhost/3000/api/getStudent), a ...

The map function appears to be malfunctioning or there may be an issue with the retrieved data

Encountering an error message that says "Cannot read properties of undefined (reading 'map')" while attempting to render a list. Below is the code snippet, seeking assistance. import React, { Component } from 'react' // import axios fro ...

Retrieving data from MongoDB and saving it to your computer's hard drive

I've asked a variety of questions and received only limited answers, but it has brought me this far: Mongoose code : app.get('/Download/:file(*)', function (req, res) { grid.mongo = mongoose.mongo; var gfs = grid(conn.db); var fi ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

What is the most efficient method for storing and retrieving numerous DOM elements as JSON using the FileSystem (fs) Module in Node.js?

Is there a way to efficiently save dynamically added DOM elements, such as draggable DIVs, to a file and then reload them later on? I am looking for the most organized approach to achieve this. ...

Is there a way to send a post request containing a base64 encoded image?

I am currently developing an image upload component in Vue.js that includes a custom cropping option. The cropped version of the image is saved in my state as a base64 string, like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAAHgCAYAAAB91L6 ...

Personalized prefix for Angular and WebStorm components

After starting a project in Angular with Visual Studio Code a few months ago, I decided to switch to WebStorm and upgraded the project to Angular 4.0 today. Although my project is running smoothly without any errors, I encountered an issue in WebStorm: ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

Error with Firebase authentication on a Next.js project using TypeScript

I recently started a personal project using Next.js, Typescript, and Firebase for authentication and database management. While working on a sign-in page with Google integration, I encountered an error labeled as auth/argument-error. According to the Fireb ...