Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to load a react module as node module

I have a react component in the path src/components/test

import React from 'react';
import ReactDom from 'react-dom';

class TestComp extends React.Component {}
export default TestComp;

I am exposing the component in index.js from path src/index.js

import TestComp from './components/test';
export {
  TestComp
};

I have added main in package.json as "main": "src/index.js"

I have published a npm package test-comp of above application and using same in another application. main.js

import {TestComp} from 'test-comp';

I am using grunt-browserify in this application with following options set.

options: {
        "transform": [
          [
            "babelify",
            {
              "presets": [
                "es2015",
                "react",
                "stage-0"
              ]
            }
          ]
        ],
        browserifyOptions: {
          debug: true,
          extensions: ['.js', '.jsx'],
          entries: ['main.js']
        }
      }

When I run grunt browserify getting following error.

>> import TestComp from './components/test';
>> ^
>> ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Warning: Error running grunt-browserify. Use --force to continue.

It probably not understanding the path mentioned in node module or rejecting to understand the same which linting. I even have tried adding following in .eslintrc but no luck

{
  "extends": "eslint:recommended",
  "parserOptions": {
      "ecmaVersion": 6,
      "sourceType": "module"
  },
  "env": {
      "browser": true,
      "es6": true
  },
  "ecmaFeatures": {
      "modules": true
  }
}

I tried most of SO answers related to this error. But still stuck in same place.

EDIT I am able to browserify first module directly with almost similar configuration. Getting this error when first module is loaded as node dependancy in other application as explained above.

like image 768
thecodejack Avatar asked Mar 01 '17 06:03

thecodejack


1 Answers

So you wrote the module test-comp in ES6, using import and export, and the main entry of the package.json in test-comp refers to src/index.js.

The answer is that browserify transforms don't apply to every module you require. They only apply to the immediate project: not the project's dependencies.

If you want to require a module that uses ES6 syntax in browserify, you'll either need to

  1. Add a prepublish script to test-comp that transpiles it to ES5, and change the main entry of test-comp to refer to that ES5 version, not the ES6 version
  2. Add babelify as a dependency of test-comp and add babelify as a browserify transform in the package's 'browserify' entry, as documented in babelify.
like image 110
tmcw Avatar answered Oct 03 '22 03:10

tmcw