Cannot import ES2015 module

2019-09-12 17:07发布

问题:

I'm trying to develop an npm library, but when I use it in another app, e.g.:

import React from 'react';
import SmallGrid from 'react-smallgrid';


export default class Library extends React.Component{

I get the following error:

$ grunt browserify
Running "browserify:jsx" (browserify) task
>> /Users/me/code/myapp/node_modules/react-smallgrid/src/smallgrid.jsx:1
>> import React from 'react';
>> ^
>> ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Warning: Error running grunt-browserify. Use --force to continue.

The library starts with:

import React from 'react';
import _ from 'lodash';


export default class SmallGrid extends React.Component{

Is there anybody here that knows what these horrible javascript errors mean?

回答1:

Currently it is not possible to import code from node_modules written in ES2015. You have to compile code in your library to ES5. For example using babel (via npm script):

"scripts": {
    "compile": "babel --presets es2015,stage-0 -d lib/ src/"
}

This script expects your ES2015 code to be placed in src/ directory and outputs compiled code into lib/ directory



回答2:

Your entry point to the library is "main": "src/smallgrid.jsx".

What this means is that you're trying to serve the source files from your package rather than the compiled ones.

Change to "main": "dist/js/smallgrid.js" in your package.json