Tjorriemorrie
Tjorriemorrie

Reputation: 17292

Browserify cannot find npm module

I'm trying to create an NPM module with great pain: react-smallgrid

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


export default class SmallGrid extends React.Component{

Compiled with:

browserify: {
    options: {
        transform: [
            ['babelify', {
                presets: ['react', 'es2015']
            }]
        ]
    },

    jsx: {
        files: {
            './dist/js/smallgrid.js': [
                './src/smallgrid.jsx',
            ]
        }
    },

When I import the js file in another project/jsx and try to browserify that, it gives the error:

Error: Cannot find module './ReactMount' from '/Users/me/code/react-smallgrid/dist/js'

I thought it's already compiled for use? I don't understand this.

Meanwhile

I've tried building it with webpack, which gives the following output:

> webpack -p

Hash: 00fd87c95d39230bd485
Version: webpack 1.12.11
Time: 14002ms
       Asset    Size  Chunks             Chunk Names
smallgrid.js  248 kB       0  [emitted]  smallgrid
    + 160 hidden modules

WARNING in smallgrid.js from UglifyJs
Condition always true [./~/react/lib/ReactMount.js:764,0]
Condition always true [./~/react/lib/findDOMNode.js:46,0]
Condition always true [./~/react/lib/instantiateReactComponent.js:80,0]

Still does not work.

Upvotes: 20

Views: 1651

Answers (2)

Inanc Gumus
Inanc Gumus

Reputation: 27932

You need to make React libs available to your code.

Run this to add browserify-shim:

npm i browserify-shim -D

Add this to your package.json:

"browserify": {
  "transform": [
    "browserify-shim"
  ]
},
"browser": {
  "react": "./node_modules/react/dist/react.js",
  "react-dom": "./node_modules/react-dom/dist/react-dom.js",
  "lodash": "./node_modules/lodash"
},
"browserify-shim": {
  "./node_modules/react/dist/react.js": "React",
  "./node_modules/react-dom/dist/react-dom.js": "ReactDOM",
  "./node_modules/lodash": "lodash"
}

By the way, you can also use browserify externals in your config to further reduce the resulting package. It's best to not include for example: React in your bundle.


Note:

I also sent you a PR in Github for the solution.

Upvotes: 2

J. Mark Stevens
J. Mark Stevens

Reputation: 4945

Your problem appears to be that you are providing the transpiled code as your library. The transpiled code includes ReactMount internally. You should be providing the source code for use as a library. Then it will transpile correctly with browserify. Look at any other npm libraries and I think you will see they provide the source to use in your imports.

As you indicated in your comment. @madox2 in Cannot import ES2015 module replied with;

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

So, npm install -g babel babel-preset-es2015 babel-preset-stage-0. Then npm run compile. That should put your transpiled code into dist/js.

Upvotes: 0

Related Questions