Create react app with browserify has error - javascript

I am learning React and try to create a simple React application.
I want to use ES2015 modules and some ES6 features so I installed Babel and browserify via npm.
These are node modules that I installed:
babel
babel-preset-es2015
babel-preset-react
babelify
browserify
gulp
reactify
vinyl-buffer
vinyl-source-stream
react
react-dom
I want to make script into several files (like itemComponent as React) and merge them into dist/app.js that actually website loads. For this, I used gulp!
This is my gulpfile.js:
var source = require('vinyl-source-stream');
var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify');
var babelify = require('babelify');
gulp.task('default', function() {
return browserify('./source/' + file)
.transform(babelify, { presets: ["es2015", "react"] })
.bundle()
.pipe(source(file))
.pipe(gulp.dest('./dist'));
});
Gulp is actually working well, everything is transpiled good without error. But check the website, it says:
app.js:19474 Uncaught ReferenceError: React is not defined
So I removed react and react-dom installed via npm, and just download React and load from HTML simply just use script tag, and it works.
But I want to include react like this:
import React from 'react';
But it is not working. This is my app.js:
import React from 'react';
import ReactDOM from 'react-dom';
import ItemList from './components/itemlist';
let items = [ ... ];
class App extends React.Component {
render() {
return (
<div>
<h1>List of items:</h1>
<ItemList items={this.props.items} />
</div>
)
}
}
ReactDOM.render(<App items={items} />, document.getElementById('app'));
I don't know what is the problem and I don't want to load each react file using script tag. Is there something I missed?

Reason of this issue were I forgot to import React module in child components, .
JSX will transpile to something like React.createElement, but there wasn't React exists so that's why I have Reference Error.

Related

Include full file path in esbuild compiled output

I want to get this file as a es module in my browser.
HelloApp.tsx
import React from "react";
import { render } from "react-dom";
function HelloApp(props: any): React.ReactElement {
return <div>Greetings</div>
}
render(
<HelloApp />,
document.getElementById("app")
);
I'm running npx esbuild ./**/*.tsx --outdir=esbuilt --format=esm
Output:
import React from "react";
import {render} from "react-dom";
function HelloApp(props) {
return /* #__PURE__ */ React.createElement("div", null, "I'm a component");
}
render(/* #__PURE__ */ React.createElement(HelloApp, null), document.getElementById("app"));
These imports aren't usable by the browser. Ideally, the path would be something like import React from "/scripts/react.js"
How do you tell esbuild to write imports like that?
The imports cannot be resolved as they are not included in the bundle. This should work if you add the --bundle argument. Also, you should use a specific file as the entry point for the bundle instead of passing a glob pattern.
Example:
npx esbuild src/app.tsx --bundle --outdir=esbuilt --format=esm
When generating a bundle, instead of --outdir you can use the --outfile argument to define the bundle file name. You probably also want to minify the bundle for the browser with the --minify argument, specify the target environment for the browsers you want to support with --target and you might want to add sourcemap support with --sourcemap.
The build command becomes:
npx esbuild src/app.tsx --bundle --minify --sourcemap --target=chrome58,firefox57,safari11,edge16 --outfile=esbuilt/app.js --format=esm

Trying to remove 'react-hot-loader' from final bundle using webpack ignorePlugin

This is what the react-hot-loader DOCs says:
https://www.npmjs.com/package/react-hot-loader
Note: You can safely install react-hot-loader as a regular dependency instead of a dev dependency as it automatically ensures it is not executed in production and the footprint is minimal.
Even though it says that. My goals are:
I want to remove react-hot-loader from my production bundle.
And I also want a single App.js file. That should work for DEV and PROD.
The only command that I have related to react-hot-loader is inside of my App.js file:
App.js
import { hot } from 'react-hot-loader/root';
import React from 'react';
import Layout from './Layout/Layout';
function App() {
console.log('Rendering App...');
return(
<Layout/>
);
}
export default process.env = hot(App);
If I run it just like this, I end up with the following line on my app.js transpiled and bundled file:
/* WEBPACK VAR INJECTION /(function(process) {/ harmony import / var react_hot_loader_root__WEBPACK_IMPORTED_MODULE_0__ = webpack_require(/! react-hot-loader/root */ "wSuE");
That's expected.
But if I change my App.js file to:
AppV2.js
import { hot } from 'react-hot-loader/root'; // KEEPING THE IMPORT
import React from 'react';
import Layout from './Layout/Layout';
function App() {
console.log('Rendering App...');
console.log(window);
return(
<Layout/>
);
}
// export default hot(App); <--- COMMENTED OUT THE hot() LINE
export default App;
And I add this line to my webpack.config.js
webpack.config.js
plugins:[
new webpack.IgnorePlugin(/react-hot-loader/)
]
I'll end up with a new transpiled app.js file with this line:
*** !(function webpackMissingModule() { var e = new Error("Cannot find module 'react-hot-loader/root'"); e.code = 'MODULE_NOT_FOUND'; throw e; }());
Note: The first '***' chars in the line above don't really exist. I had to add them in order to the ! exclation mark to be shown in the quote. Don't know why but you can't start a quote with an exclamation mark.
QUESTION
Isn't the IgnorePlugin supposed to completely ignore the react-hot-loader package? Why is it being marked as missing? See that it's not even being used on the code (since I've commented out the hot() call).
Ignore Plugin only excludes that particular module in bundle generation. However it will not remove the references to the module from your source code. Hence your webpack output is throwing that error.
One way of bypassing this error is to use the DefinePlugin to create a dummy stub for react-hot-loader. More on that here.
That said react-hot-loader itself proxies the children without any changes if the NODE_ENV is production. Check here and here. So in production mode apart from the hot() function call which directly returns your component, there is no other stuff that happens.
Another option could be:
// App.js
export default function AppFactory() {
if (process.env.NODE_ENV === "development") {
return hot(App);
} else {
return App;
}
}
// index.js:
import AppFactory from './App';
const App = AppFactory();
// ...
<App />
Now since webpack is creating bundles at build time, it knows if the mode is development or production (more on build modes) and should be able to eliminate the dead code with tree shaking and UglifyjsWebpackPlugin.
Make sure that if you are using Babel it's not transpiling your code to CommonJS - see Conclusion section, point 2 of the tree shaking page.
Pass the ambient mode to babel.
"scripts": {
"build-dev": "webpack --node-env development",
"build-prod": "webpack --node-env production",
},

How can I export multiple React components in reusable NPM package so they can be imported independently & exclude dependencies from app bundles?

Can I make an NPM package containing multiple React Components that can be independently imported in consuming apps?
I have a NPM package with two reusable React components. The one component imports a heavy/sizeable 3rd party library. The other component does not import this 3rd party library.
I would like to be able to use these components in consuming apps and only include the heavy 3rd party library in my app bundles if I have imported the reusable component that imports the heavy library.
Is there a way to setup my reusable package that will not include the 'heavy-library' in my app bundle if I do not use the HeavyWeight component?
// My NPM package
// components/HeavyWeight.js
import React from 'react';
import heavyLibrary from 'heavy-library'; // This component imports a very heavy library
const HeavyWeight = () => {
const a = heavyFunction();
return (
<div>
{a}
</div>
);
}
export default HeavyWeight;
// components/LightWeight.js
import React from 'react';
const LightWeight = () => {
return (
<div>
I'm light weight.
</div>
);
}
export default LightWeight;
// index.js
import HeavyWeight from './components/HeavyWeight';
import LightWeight from './components/LightWeight';
export { HeavyWeight, LightWeight};
// webpack.config.js
// ...
module.exports = {
//...
externals: {
heavy-library: 'heavy-library'
}
};
// Two of my apps using my reusable components
// appA.js
// Bundling this app should include 'heavy-library' in final webpack bundle
import { HeavyWeight } from 'reusable-package';
// appB.js
// Bundling this app should not include 'heavy-library' in final webpack bundle
import { LIghtWeight } from 'reusable-package';

React, webpack and creating a bundle using a per build json?

We would like to create bundle.js from React and webpack, where a per build configuration is included and made available to the React code, but we are not sure how to go about doing this.
The idea would be to be to do something like:
npm run build -- config="config123.json"
And then have the generated bundle.js include that configuration, such that it could be used by the root container. Something like:
import React from 'react';
import ReactDOM from 'react-dom';
import RootContainer from './containers/main-container';
ReactDOM.render(
<RootContainer config={configPassedByBuildProcess}/>,
document.getElementById('app')
);
Is this possible and if so, how should we approach this?
No, I don't believe that you can pass a file on build, from what I know the only thing that you can pass is a string like an ENV variable. You could import the config123.json file like this
import React from 'react';
import ReactDOM from 'react-dom';
import RootContainer from './containers/main-container';
import config from '/path/to/config123.json'
ReactDOM.render(
<RootContainer config={config}/>,
document.getElementById('app')
);
You may need a JSON loader for importing JSON files
After a bit of experimenting, the solution I have found is to use Webpack's DefinePlugin, since this provides a way of doing string substitution during webpack's build phase.
In my React code I defined:
// Will be substituted by webpack's DefinePlugin. Not an error.
const bundleConfig = BUNDLE_CONFIG;
and then in my webpack.config.js I first load my config (hard coded for now):
// The path can be pulled in via 'process.args' and parsed as appropriate
const bundleConfig = fs.readFileSync('bundle-config/default-config.json', 'UTF-8');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'BUNDLE_CONFIG': bundleConfig
})
]
}
Note that if for some reason we want to build with a missing or undefined bundleConfig, then the right substitution would likely be the string (not the keyword) 'undefined' , to keep the code valid, such that:
const bundleConfig = 'undefined';
module.exports = {
plugins: [
new webpack.DefinePlugin({
'BUNDLE_CONFIG': bundleConfig
})
]
}
Just one extra thing was the configuration of the package.json (scripts section only):
{
"scripts": {
"build": "run() { NODE_ENV=production && webpack -p $1; }; run",
}
}
This allow passing in the path to the webpack.conf.js script, when we call:
npm run build /path/to/config.json

ReactJS - Babel usage problems to compile .jsx

For a quick test, i've created my main.jsx file written in ES6 for my ReacJS app:
main.jsx
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link } from 'react-router'
class TestComponent extends React.Component {
render() {
return <div className="test">...</div>;
}
}
Then i compile my code with browserify and babel:
browserify -t babel main.jsx -o public/js/bundle.js
I get this error: Error: Cannot find module 'babel'
What's the cleanest way to compile ES6 code with ReactJS?
If you are using Browserify, you can use the transform 'babelify' to compile your ES6 code. Check it out here:
https://github.com/babel/babelify

Categories