I’m trying to import a react component from a beta framework called plygrid. I install this framework with:
$ npm install plygrid --save
I then try to import one of its react modules by:
import button from 'plygrid/react_components/button.jsx';
When I do this I get an error:
Uncaught SyntaxError: Unexpected token import
However, if I simply copy that component’s code into the
/imports directory, without change the code whatsoever, it works fine. This seems like a bug to me, if the same code works in the imports directory, shouldn’t it work from an npm package?
There are a few reasons why it won’t work directly:
- You’re missing a proper entry point file. Create an
index.js in your package root for example, and reference it using
main in your package.json.
- Your components are stored in your package using ES2015 module syntax. To make sure your code is compatible with as many environments as possible, you should aim to only publish ES5 compatible JS. That means your npm package should use export/require syntax. You can still leverage ES2015 import/export syntax in your source, but you’ll want to have things compiled down to export/require syntax as part of an npm pre-publish build step (for more info see Writing NPM packages with ES6 using the Babel 6 CLI).
- It looks like you’re trying access your JSX files directly from your npm package. Your JSX files should be compiled into JS, stored with your npm package, then made accessible via export/require syntax. This can also be handled as part of an npm pre-publish step (take a look at Publishing your first React component on NPM for more info).
For a good example of how this all works pick a popular react component package, crack open their
package.json, and take a look at how they’re handling their build/publish process. For example, take a look at how the react-bootstrap package is handling this (they’re using ES2015 modules and converting everything via a build/pre-publish step).