2

I have written a node module and published it as a node package. It works when I use it in backend applications (pure nodejs, no babel or transpile).

However, when I use this same npm module in the frontend (in my case a 'create-react-app') application, it breaks. Bellow is the exact error:

Module parse failed: Unexpected token (14:2)
You may need an appropriate loader to handle this file type.

The error is referring to my use of the spread operator (...). I would prefer not to have to rewrite the library, and would rather add some kind of transpiler to package my library. I haven't found a clear solution to this, they are all very convoluted.

I have tried using rollupjs, and https://github.com/insin/nwb. Neither sadly seem to be what I'm after.

Run my code:

You can install the library to your create react app using npm i cbs-proxy-client@0.0.3. And then add the line const cbsProxyClient = require('cbs-proxy-client') or import cbsProxyClient from 'cbs-proxy-client' to any of your scripts.

Advice would be appreciated :)

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
JasoonS
  • 1,432
  • 3
  • 13
  • 26

1 Answers1

2

A library used for frontend is expected to package an already transpiled version of the source javascript. To do this, you might want to use rollup as a build process in your library to create a bundle file. You can use babel to transpile your code for desired browser support. Let's say the bundle file is saved in dist/bundle.js. Now you will modify the package.json to load this bundled file as the entry file using main parameter in package.json

If you are building using rollup or webpack, it is easy to miss that the bundled file should be prepared as a library. This means that importing the file using commonjs should be able to export correct variables. A typical webpack build removes such exports because it is supposed to work straight on a browser. This blog is in my bookmarks titled "js library steps" since I was creating my first js library.

Note that you do not need to put your generated file in version control. You can use npm files property in package.json to package your bundled files while ignoring them in git.

cnvzmxcvmcx
  • 1,061
  • 2
  • 15
  • 32
  • Thank you for the answer. This whole thing is unnecessarily complicated. I'm still getting errors form various things, and having issues with the `fetch` function. I've tried `fetch everywhere`, `isomorphic-fetch` , and `fetch-ponyfill` and getting errors with all of them. My sollution now is to fork the package and make one version for the backend, one for the frontend. The frontend version I'll try use https://github.com/insin/nwb since I'm still getting errors with https://github.com/krasimir/webpack-library-starter – JasoonS Aug 05 '18 at 13:53