PapaParse icon indicating copy to clipboard operation
PapaParse copied to clipboard

Cannot be used in a Node.js ESM environment: Named export 'parse' not found

Open cdauth opened this issue 3 years ago • 2 comments
trafficstars

When attempting to import PapaParse from a Node.js ES module, the following error is shown:

import { parse } from "../../node_modules/papaparse/papaparse.js";
         ^^^^^
SyntaxError: Named export 'parse' not found. The requested module '../../node_modules/papaparse/papaparse.js' is a CommonJS module, which may not support all module.exports as named exports.

As a workaround, PapaParse can be imported using import papaparse from 'papaparse' and then accessing the function using papaparse.parse. As a workaround in code that is shared by the frontend and backend, PapaParse can be imported in the following way:

import * as papaparse from 'papaparse';
const { parse } = ((papaparse as any).default ?? papaparse) as typeof papaparse;

To fix the issue, PapaParse needs to publish a 3rd bundle in ESM format. The bundle needs to have the .mjs file extension and does not have to be minified or contain any shims or transpilations to support old browsers. Then the following export map needs to be added to package.json:

  "exports": {
    ".": {
      "import": "./papaparse.mjs",
      "require": "./papaparse.js"
    },
    "./*": "./*"
  }

The wildcard export at the end is to provide backwards compatibility with existing projects that are importing PapaParse in unusual ways.

cdauth avatar Jun 15 '22 20:06 cdauth

Note that name-importing from CommonJS works if the exports look like this (more information):

exports.namedExport = 'yes';

rauschma avatar Oct 26 '22 20:10 rauschma

Try this:

import {default as papa} from "papaparse"

professorf avatar Nov 20 '22 22:11 professorf