alexcaza / export-to-csv

Export a JS collection to CSV; written in TypeScript.
Other
207 stars 48 forks source link

Unable to resolve path to module 'export-to-csv' after upgrading to v1.2.3 #88

Closed Catravine closed 6 months ago

Catravine commented 8 months ago

after reinstalling my packages today, I got export-to-csv v1.2.3, which caused my project not to compile; freezing the version at 1.2.2 restored functionality.

having 1.2.3 installed, then the command npm start, produces the error: Failed to compile.

./src/appReportTables/reportTableHelpers.js Module not found: Can't resolve 'export-to-csv' in [...path../appReportTables]

macOS ventura 13.6.3

file referencing export-to-csv (in use with tanstack table)

import { jsPDF } from 'jspdf'; 
import autoTable from 'jspdf-autotable';
import { mkConfig, generateCsv, download } from 'export-to-csv'; 

export const handleExportRows = (table, subject, format) => {
  const CSV = 'csv'
  const subjectChoice = typeof(subject) === 'string' ? subject : 'data';
  const FW_FILENAME = `fleetwatcher-${subjectChoice}-`;
  const formatChoice = typeof(format) === 'string' && format.toLowerCase() === CSV ? 'csv' : 'pdf'; // maybe more later ??
  const visibleCols = table.getAllColumns().filter((c) => 
    c.columnDef.header.length > 0 && c.getIsVisible()
  );
  const visibleRows = table.getFilteredRowModel().rows;
  const tableHeaders = visibleCols.map((c) => c.columnDef.header);
  const tableData = visibleRows.map((r) => visibleCols.map((c) => r.original[c.id]));
  const dateStamp = (new Date()).toISOString().replace(/[^0-9]/g, "").slice(0, -3);
  if (formatChoice === 'pdf') {
    const doc = new jsPDF();
    autoTable(doc, {
      head: [tableHeaders],
      body: tableData,
    });
    doc.save(FW_FILENAME + dateStamp + '.pdf');
  } else { // CSV; maybe more formats later ??
    const csvConfig = mkConfig({
      fieldSeparator: ',',
      decimalSeparator: '.',
      filename: FW_FILENAME + dateStamp + '.csv',
      columnHeaders: visibleCols.map((c) => { return {key: c.id, displayLabel: c.columnDef.header}})
    });
    const rowData = visibleRows.map((row) => row.original);
    const csv = generateCsv(csvConfig)(rowData);
    download(csvConfig)(csv);
  }
};
alexcaza commented 8 months ago

Could you share your package.json, please?

It's possible your—I'm assuming react app—isn't set to work with ES modules, which is why suddenly version 1.2.3 no longer works with your app (this should've been the behaviour starting with version 1, but I overlooked some build configuration stuff to make it a proper ES module).

There are more details here about ESM vs CommonJS: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

ranveer-pulse commented 8 months ago

facing same issue

sambev commented 8 months ago

Maybe not the same exact issue, but seeing a similar error in our project (React and Typescript). We exclusively use ES modules, but see this error in Typescript (same thing for any export of the library):

Module '"export-to-csv"' has no exported member 'mkConfig'.

27 import { mkConfig, generateCsv, download } from "export-to-csv";
            ~~~~~~~~

The code compiles fine and works as we expect it to, but Typescript isn't happy about it and can't seem to find the correct (maybe any?) type information from the module. Can also confirm that 1.2.2 does NOT error and seems to have proper type information.

Any suggestion/pointers on where to look? Happy to provide more info.


  System:
    OS: macOS 14.3
    CPU: (8) arm64 Apple M1 Pro
    Memory: 102.22 MB / 16.00 GB
    Shell: 3.6.1 - /opt/homebrew/bin/fish
  Binaries:
    Node: 18.12.1 - ~/.volta/tools/image/node/18.12.1/bin/node
    Yarn: 1.22.19 - ~/.volta/tools/image/yarn/1.22.19/bin/yarn
    npm: 8.19.2 - ~/.volta/tools/image/node/18.12.1/bin/npm
  Browsers:
    Chrome: 122.0.6261.94
    Safari: 17.3
  npmPackages:
    typescript: ^4.9.5 => 4.9.5
    vite: ^5.0.0 => 5.0.12
alexcaza commented 8 months ago

If you could share your tsconfig.json @sambev that would be great 😄 I'll try to reproduce it in the meantime with the information that I have. I do find it really strange that Typescript isn't picking up on the .d.ts files, though 🤔 .

It's possible it's not the exact same issue as @Catravine is experiencing, though, since they seem to be in the context of a js react project, and I suspect their issue is due to it being built for CommonJS instead of ES Modules, which has some different implications!

sambev commented 8 months ago

Here is my tsconfig.json

{
  "exclude": ["node_modules", "dist"],
  "compilerOptions": {
    "baseUrl": "./app/frontend",
    "esModuleInterop": true,
    "jsx": "react",
    "paths": {
      // Alias any @/ imports to the root path so we can use absolute imports
      // more consistently with typescript. Update the vite config if you
      // change this to something else
      "@/*": ["./*"]
    },
    "skipLibCheck": true,
    "strict": true,
    "typeRoots": ["./node_modules/@types", "app/frontend/types", "app/frontend/modules/shared/charts/types"]
  }
}

I'm trying to test different configuration options with the module option, but I end up getting a lot of other errors.

FWIW, I'm trying to get a reproduction case with a small basic vite template, but have been unable so far. I'll keep trying.

razvanGit1 commented 8 months ago

I have the same issue like @sambev. Also I tried the automatic import from Intellij (to get mkConfig for example - import {mkConfig} from "export-to-csv/output/lib/config";), but then I am having another issue. Can't build because:

Error: node_modules/export-to-csv/output/lib/generator.d.ts:2:46 - error TS2691: An import path cannot end with a '.ts' extension. Consider importing './types.js' instead.

2 import { CsvOutput, ConfigOptions, IO } from "./types.ts";

I think it is configuration issue, maybe I need something else in tsconfig file.

alexcaza commented 8 months ago

@sambev Since you don't have an explicit target or module set in your tsconfig.json, you're likely defaulting to CommonJS (CJS), which is why it suddenly stopped working. Before v1.2.3, .d.ts files were built incorrectly (my bad) and tsc was building them for CJS.

If you look at the Typescript tsconfig docs, you'll see that the defaults are pretty "safe" (read older).

The default for target is es3 and the default for module if target: 'es3' is commonjs.

I used stackblitz to build test in a new vite project, and it works fine. Looking at the tsconfig.json in the project, you can see that the module and target settings are much more modern. Here's the stackblitz: https://stackblitz.com/edit/vitejs-vite-u9lsey?file=src%2Fmain.ts

I'd recommend trying to change your tsconfig.json settings to see if you can build your project that way.

@razvanGit1 import {mkConfig} from "export-to-csv/output/lib/config" doesn't actually contain a file with compiled javascript code, just type signatures for typescript, which is probably why it's throwing an error. Depending on your tsconfig, you might be running into a similar issue as sambev, so I'd start with reading up on the two typescript links I referenced above. If that doesn't help anything, feel free to share your tsconfig as well and more details about your project.

nikitalukash01 commented 8 months ago

@alexcaza same issue as for @razvanGit1 my .tsconfig:

{ "compilerOptions": { "target": "ES5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "ESNext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": [ "src" ] }

alexcaza commented 8 months ago

@nikitalukash01 I copy-pasted your tsconfig.json into the stackblitz project I posted above and the project was built and ran without issues.

I'm not sure what else the issue could be. I wonder if it might be a typescript versioning issue with your editor, or if it's using another internal config for the editor and not your project config.

Feel free to try it yourself by replacing the contents of tsconfig.json in this project with yours: https://stackblitz.com/edit/vitejs-vite-u9lsey?file=src%2Fmain.ts

You could try adding allowImportingTsExtensions, but you need to have a build tool that isn't tsc for this setting to work. The typescript docs I linked will make the side-effects of enabling this clear.

titusdecali commented 7 months ago

I have this and am NOT using typescript

alexcaza commented 7 months ago

@titusdecali could you check to see if your package.json has "type": "module" set?

Like I replied to OP in this comment, I suspect the error comes from not having ES Modules enabled in your project.

The complexity of enabling ES Modules might require more than only adding/changing that property in your package.json. If you're using Webpack, Vite, Rollup, etc. the changes might be more involved.

I'm not really in a position to help with each person's bespoke issues that come up within their build config since it's unrelated to the project. All I can do it point people in a direction. Which in this case, has to do with projects likely not being set to use ESM (which is, unfortunately, the default behaviour of node init).

titusdecali commented 7 months ago

@alexcaza Thanks for the response. I was able to solve the issue, but it seemed unrelated to type: module It was an old project and I was bumping packages. Perhaps by updating node the issue was resolved, though I can't say for sure.

alexcaza commented 7 months ago

@titusdecali great! I'm happy to hear it was resolved. :) it's possible it was an old version of Node.

I'm going to keep this issue open for a few more days, and if I don't hear back from anyone else in the thread, I think I'll close it for now.

VladislavRusin commented 7 months ago

I have the same issue as @sambev. Trying import { generateCsv, asString } from 'export-to-csv'; but get an error: error TS2305: Module '"export-to-csv"' has no exported member 'generateCsv' Here is my tsconfig.json

{
  "compilerOptions": {
    "lib": ["dom", "ES2018", "ES2019"],
    "target": "ES2019",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "./build",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "noImplicitOverride": true,
    "strictNullChecks": true,
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "types": ["node", "preact"]
  },
  "include": ["./src/**/*"],
  "exclude": ["node_modules"]
}

Node version: 18

VladislavRusin commented 7 months ago

I have found out following changes in version 1.2.3: added flag "allowImportingTsExtensions": true in tsconfig.json which is not supported in old TS versions. So if your typescript version doesn't support this flag you can't use versions higher than 1.2.2

thuanpt283 commented 7 months ago

I have found out following changes in version 1.2.3: added flag "allowImportingTsExtensions": true in tsconfig.json which is not supported in old TS versions. So if your typescript version doesn't support this flag you can't use versions higher than 1.2.2

I have the same issue as @VladislavRusin and I was tried and this is exactly us issue.

Thanks @VladislavRusin save my day 💯

thuanpt283 commented 7 months ago

I was able to solve the issue by upgrade version Typescript form 4.9.5 to 5.4.3.

alexcaza commented 6 months ago

I'm closing this issue for now but for anyone who comes across this in the future, I've listed the key takeaways below.

Typescript users

If you're having build issues, try upgrading to Typescript v5 or later.

Javascript users

The crux of this issue was that from v1.2.2 to v1.2.3 of the library, some changes were made to properly build the project to use ES Modules. Before v1.2.3, the build output was incorrect for use as a true ES Module due to a configuration issue. This is why the minor version "broke" as it was an oversight on my part while switching to ES Modules for v1.

If these fixes don't work, and you've tried what others suggested in the thread above, feel free to open a new issue 😄

Be sure to follow the issue template and include which versions of node, typescript, etc you're using.