Fraction.js icon indicating copy to clipboard operation
Fraction.js copied to clipboard

Bundling with Vite/Usage in SvelteKit

Open lmcgartland opened this issue 3 years ago • 5 comments

Using fraction with the Vite bundler and TypeScript gives the following warning: fraction.js doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.

When attempting import Fraction from "fraction.js the bundler throws the following error: TypeError: __vite_ssr_import_2__.default is not a constructor

I've tried adding "fraction.js" to the vite config ssr.noExternal and optimizeDeps.include but that doesn't resolve the issue.

Note this error only occurs seemingly when server side rendering the page (using SvelteKit). If the lib is loaded client side, the library works as expected.

tsconfig.js has both "allowSyntheticDefaultImports": true and "esModuleInterop": true

Any thoughts as to why the bundler is not liking importing Fraction on the server?

lmcgartland avatar May 04 '22 05:05 lmcgartland

Did you try the following?

import Fraction from 'fraction.js';

infusion avatar May 22 '22 13:05 infusion

I had the chance on a project to run it locally on svelte and both npm run dev and npm run build works without problems for me (where vite builds the bundle). Is this still a problem for you or do you see any problems on Fraction.js how something is exported?

infusion avatar Oct 31 '22 12:10 infusion

just had the same problem with astro (uses vite under the hood). Could "fix" it by adding this to the config:

  vite: {
    ssr: {
      // Example: Force a broken package to skip SSR processing, if needed
      external: ['fraction.js'], // https://github.com/infusion/Fraction.js/issues/51
    },
  },

without this, I also get

fraction.js doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.

and getting this error on pages where fraction.js is used on the server (seemingly):

Cannot set properties of undefined (setting 'Fraction')

I've tried both ways to import, but the problem only goes away with the config above

felixroos avatar Jan 28 '23 19:01 felixroos

The error probably comes from this line. The root variable has been removed since node 14. globalThis might be the thing to go for (please double check)

felixroos avatar Jan 28 '23 19:01 felixroos

The root variable comes from here https://github.com/infusion/Fraction.js/blob/master/fraction.js#L40

infusion avatar Jul 07 '23 23:07 infusion