Cannot resolve module 'react' when using npm link and webpack - reactjs

I am writing an external module that I would like to require in my project (react-list)
my module is a react component and obviously I have this in top of my file
var React = require('react');
I'm using npm link, and in my project I'm getting an error from webpack that react doesn't exist inside the node_modules directory INSIDE the external module
ERROR in /web/react-list/dist/List/List.js
Module not found: Error: Cannot resolve module 'react' in /web/react-list/dist/List
why isn't it requiring the react component from my projects node_modules directory?
edit: added my webpack, had to redact the files and directories
'use strict';
module.exports = {
context: __dirname,
entry: {
....
},
output: {
path: '../public/js/pages',
filename: "[name].js"
},
devtool: 'source-map',
resolve: {
modulesDirectories: ["node_modules", ......],
extensions: ['', '.js', '.jsx']
},
plugins: [],
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ["react", "es2015-loose"]
}
}
]
}
};
edit 2: I found a workaround without using npm link, and simply installing the required package using npm install and then removing the dist directory and replacing it with a soft link on my own without npm's help. Obviously this isn't an ideal way to develop.
edit 3: I reach the dreaded refs must have owner issue https://facebook.github.io/react/warnings/refs-must-have-owner.html error if I try to install the dependencies on my package directory, so its either this package doesn't find a react directory or it does but with another react version and nothing works...

Related

Webpack unable to find babel-loader

I'm having a bit of trouble adding react to a legacy application. While I found plenty of materials on getting started, I ran into a bunch of issues related to my particular configuration and exacerbated by my utter lack of webpack knowledge (so much time relying on react cli tools makes one lax).
My configuration:
./docs/jslib = my node_modules, that's where yarn installs modules
./docs/jscripts = my general js folder, various js scripts go there
./docs/jscripts/mini = my dist folder, some things get built/packed by gulp and end up here. This is where the built things are expected to go
./docs/jscripts/react(/react.js) = my desired root for react things, where the react.js is the entrypoint for DOM selection and rendering (at least for the first attempt).
My webpack config:
const path = require("path");
module.exports = {
entry: "./docs/jscript/react/react.js",
output: {
path: path.resolve(__dirname, "./docs/jscript/mini"),
filename: "react.js"
},
resolve: {
extensions: [".js", ".jsx"],
modules: [
path.resolve(__dirname, "./docs/jslib")
],
alias: {
'babel-loader': path.resolve(__dirname, "./docs/jslib/babel-loader")
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "./docs/jscript/react")
],
exclude: [
path.resolve(__dirname, "./docs/jslib")
],
use: {
loader: "babel-loader"
}
}
]
}
};
The error I get on running webpack:
yarn run v1.21.1
$ ./docs/jslib/babel-loader/node_modules/.bin/webpack --mode production
Insufficient number of arguments or no entry found.
Alternatively, run 'webpack(-cli) --help' for usage info.
Hash: 210250af48f3cf84fa4a
Version: webpack 4.41.6
Time: 75ms
Built at: 02/14/2020 9:23:09 AM
ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in '/var/www/html'
I have webpack-cli, I can run webpack straight, I can run it from the modules bin folder, it's all the same problem - it can't find babel-loader even though babel-loader brings its own webpack script which I use, so the loader is obviously there in the "node_modules" that's actually on a different path.
From what I gathered, all I had to do was to add my custom node_modules path to the webpack config under the resolve settings, which has solved my initial errors related to packages not found (yet webpack still can't find the loader).
Note: if I symlink my ./docs/jslib as ./node_modules, it works as expected.
Is there something I'm missing?
Thanks!
After some digging, I found a solution and some details that other might want to keep in mind when configuring webpack in a rather non-standard context:
resolve: points to modules that are directly required in various scripts
resolveLoader: should point to the same, for the purpose of accessing loaders (which is what I needed)
Solution:
resolveLoader: {
extensions: ['.js', '.json', '.jsx'],
modules: [
path.resolve(__dirname, "./docs/jslib")
],
mainFields: ['loader', 'main']
}

React component via custom npm package. module cannot be found

I am trying to create a custom npm package that will allow me to import some of my components over multiple projects. I wrote a simple package yesterday which can be found here: demo npm package. It's a simple starter project that has a webpack config and a uses npx babel to transpile and copy the files to the dist and lib folder.
If I include this package into my own project it works but not as I would expect. when I use the following code:
import {NavBar, HelloLib} from "testprivatenprodney;
It gives an error "Module not found".
when I use
import { NavBar, HelloLib } from "testprivatenprodney/lib/HelloLib";
it works as long as the navBar component does not have any child components. If it has I get "Module not found" error again.
I think I am missing something in my webpack configuration. yet all I can find is to have the resolve array, which is included.
const webpack = require("webpack");
module.exports = {
devtool: "source-map",
entry: "./src/index.js",
output: {
path: __dirname + "/dist",
publicPath: "/",
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.css$/,
loaders: ["style-loader", "css-loader"]
}
]
},
resolve: {
extensions: [".js", ".jsx"]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
})
]
};
any help would be much appreciated.

Module not found: Error: Cannot resolve module 'fs'

I'm making a react app using Babel and Webpack and I want to use the file-exists package from npm. I already installed and saved the package as a dependency for my project. After running npm start I get this error:
ERROR in ./~/file-exists/index.js
Module not found: Error: Cannot resolve module 'fs' in C:\GitHub\CryptoPrices\node_modules\file-exists
# ./~/file-exists/index.js 3:9-22
file-exists uses fs as a dependency but for some reason it is not working. Npm starts and runs without any issues if I don't require file-exists anywhere.
here is my webpack config file:
module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [{
// exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
I'm new to Webpack and Babel so I'm a little bit lost.
It looks like you're calling the fs file-exists method in your index.js file. I'm not sure in what context you're calling the method, but this looks like a client-side call to a server-side method. I ran into a similar issue just recently.
From what I understand, the main issue seems to be that you can't call server-side (Node) methods in browser-interpreted client-side (front end) code. You have to call them from a server.
Webpack can load the fs module code into your front end, but the browser can't actually interpret those Node methods and run them; only a Node environment can do that. (more here)
You could fix the core issue by modifying the call to fs methods to happen somewhere server-side, or by finding an equivalent browser-supported package that offers the same functionality as the fs methods you need but that can be run in a browser.
A quick search for "fs module for browser" brings up a variety of options that might work for what you need, like fs-web, browserify-fs or filer.
Here is a similar question with some insight.
Use fs module in React.js,node.js, webpack, babel,express
node: {
fs: 'empty'
}
try to add the code above to your webpack config file and the error should disappear.

Error with Typescript / whatwg-fetch / webpack

I'm trying to have a simple demo app working using Typescript and React, with webpack. When I try to add whatgw-fetch to retrieve data from a server, I get this error when running webpack :
error TS2307: Cannot find module 'whatwg-fetch'
The error is on the import line :
import * as Fetch from 'whatwg-fetch'
I did install the npm dependency and the typing for typescript
npm install --save whatwg-fetch
typings install --global --save dt~whatwg-fetch
My webpack configuration is :
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
var path = require('path');
module.exports = {
entry: [
path.resolve(__dirname, 'app/index.tsx')
],
output: {
path: __dirname + '/dist',
filename: "index_bundle.js"
},
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{test: /\.tsx$/, exclude: /node_modules/, loader: "ts-loader"}
]
},
plugins: [HTMLWebpackPluginConfig]
};
I don't see any error in my IDE (IntelliJ IDEA) and if I change the import to some module that actually is not there, I get a different error (Module not found: Error: Cannot resolve module 'whatwg-fetcha' in C:\dev\[...]), and my IDE tells me the import is not valid.
The import for basic React works fine with an equivalent setting :
npm install --save react
typings install --global --save dt~react
import * as React from 'react'
Am I missing something ?
Thanks for your help.
After some more research (and actually writing the question down), it seems that the typing for whatwg-fetch is in this use case : Import a module for side-effects only (as described on the site : Though not recommended practice, some modules set up some global state that can be used by other modules. These modules may not have any exports, or the consumer is not interested in any of their exports.)
So instead of
import * as Fetch from 'whatwg-fetch'
I used
import 'whatwg-fetch'
And I don't get any more errors and I can use the fetch function in my component. Hope this helps someone else.
Aside from #Antoine solution, I also needed to add #types/whatwg-fetch to my project to make it work:
npm install --save #types/whatwg-fetch

Webpack / Babel / React build error: "Unknown option: foo/node_modules/react/react.js.Children"

I'm trying to build a project with webpack and react with this webpack config:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
'babel-polyfill',
'./app/less/main.less',
'./app/main.js',
'webpack-dev-server/client?http://localhost:8080'
],
output: {
publicPath: '/',
filename: 'dist/main.js'
},
debug: true,
devtool: 'source-map',
module: {
loaders: [
{
test: /\.js$/,
include: path.join(__dirname, 'app'),
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.less$/,
loader: "style!css!autoprefixer!less"
},
]
}
};
I am sure I have the needed pm modules too and have webpack installed, however when running webpack I get:
Module build failed: ReferenceError: [BABEL] /Users/me/foo/app/main.js: Unknown option: foo/node_modules/react/react.js.Children
Any ideas?
Sorry I forgot to install babel-preset-react:
$ npm install babel-preset-react --save-dev
I just wanted to add that I got the error after I uninstalled an old npm module I wasn't using in my project anymore. Which was weird because I wasn't using it anywhere - how could uninstalling something that isn't used anywhere cause an error?
Turns out that one of that modules sub-dependencies had babel-preset-react, which I had missed installing to my own project when I started it. Thus, uninstalling that package also uninstalled the critical babel-preset-react!
For over a year, my react app could compile thanks to another package's sub-dependency...
So yes, installing babel-preset-react solved the issue for me.

Resources