React Webpack initial build and runtime - reactjs

I'm new to React and I'm still trying to understand how things are put together. In webpack, I understand that we have to run the webpack command initially and it will generate the index.js file where we output it in the config. For my questions:
What role does this file play in runtime?
Everytime i do an npm start, does it automatically update my index.js file?
Here is my webpack.config:
var config = {
entry: './main.js',
output: {
path: __dirname,
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
With or without initially running webpack command my code still runs, reason for me being confused as to what it really does, because even without having the index.js in my directory I'm still able to run my code

Why we are using webpack:
When we run webpack command it will create a single index.js file in given the location.Our browser understands only vanilla html, css and javascript.But with react you are probably going to use jsx or es6. So we need to transform these to what browser understands.
According to your webpack.config , webpack is going to convert all jsx file into .js file (using bable loader)and bundle it to a single file as index.js.
Role plays by index.js:
You will be having an index.html file in your app directory.webpack automatically load index.js file to body of index.html file.This if final index.js file browser is going to use.
If you are using following configuration in package.json
{
"scripts": {
"dev": "webpack -d --watch",
"build" : "webpack -p"
},
}
then webpack keeps watching any changes in .jsx file and update index.js
As you are saying you code is running without webpack.It means you are using simple .js file.But to use es6 or .jsx you need webpack.
Hope it helps!. For more you can read https://tylermcginnis.com/react-js-tutorial-1-5-utilizing-webpack-and-babel-to-build-a-react-js-app/

Related

Importing a react component into an existing react project from npm package

I have created an npm package with the scoped name '#bpmg/mycomponent' with a single react component. I have published this to a local npm registry (verdaccio).
I have created a new react project to test this package, using create-react-app.
I have installed my npm package successfully and can import the component into my project.
However, webpack (from create-react-app scripts) complains about my imported file.
support for the experimental syntax 'jsx' isn't currently enabled
So I install react-app-rewired and try to override the webpack config to "include" this one node_module in the webpack bundler.
Here is what I have
/* config-overrides.js */
const path = require('path');
module.exports = {
webpack: function (config, env) {
config.module.rules= [
{
test: /\.(js|jsx)$/,
exclude: /node_modules\/(?!(#bpmg)\/).*/,
include: [
path.join(__dirname, 'src')
],
loader: 'babel-loader',
options: { presets: ['#babel/env', '#babel/preset-react'] },
}
];
return config;
}
}
This fails to run
ERROR in ./node_modules/#bpmg/myComponent/src/myComponentMainFile.js
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
Where it chokes on the first bit of jsx syntax it encounters.
Where am I going wrong here?

create-react-app webpack configuration file

I have created a new react app using npx create-react-app and now I want to integrate a webpack.config.js file. I know I don't have to but it is a necessary step for an assignment.
I have tried many tutorials an articles but I can't seem to make it work. All I need is to include all the css related loaders (sass, css etc) and babel.
This is my webpack.config.js file:
const path = require('path');
module.exports = {
mode: "development",
entry: path.join(__dirname,'./src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader"
]
}
]
},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
output: {
path: path.join(__dirname,'public'),
filename: 'bundle.js'
},
devServer: {
contentBase: path.join(__dirname,'public')
}
};
And I get this error:
ERROR in ./src/index.js 7:16
Module parse failed: Unexpected token (7:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import * as serviceWorker from './serviceWorker';
|
> ReactDOM.render(<App />, document.getElementById('root'));
|
| // If you want your app to work offline and load faster, you can change
There're some alternatives that can override webpack config without ejecting the CRA project:
Alternatives You can try customize-cra for a set of CRA 2.0 compatible
rewirers, or any of the alternative projects and forks that aim to
support 2.0:
Rescripts, an alternative framework for extending CRA configurations
(supports 2.0+).
react-scripts-rewired for a fork of this project that
aims to support CRA 2.0
craco
add config-overrides.js in the route and add your webpack changes as:
const { addWebpackModuleRule } = require('customize-cra')
module.exports = {
webpack: override(
addWebpackModuleRule({
issuer: {
test: /\.sass?$/,
},
loader: 'file-loader',
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
}))
}
Answering this just because it kills me to see 10 page Medium articles as an answer when it can be answered in 1 sentence.
Enter your project dir and run npm run eject
This will extract all of the configuration files for you to edit, including webpack.config.js, to a folder called "config". Enter config/webpack.config.js, find the "return" statement, and inside there is a "resolve" configuration option. Add the following to that object:
symlinks: false
Boom. Saved you a stupidly long Medium article.

Webpack+SemanticUI+React: process is not defined

I have found numerous posts about the Webpack error:
Uncaught ReferenceError: process is not defined
most of which suggest adding a plugin to the webpack.config.js:
plugins: [
// ...
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
}
}),
// ...
]
however this does not seem to do the trick in my case.
To make things easy, I have created a repo with the bare minimum to setup SemanticUI-React with Webpack, which should be straightforward to navigate. My config in webpack.config.js is heavily inspired from this recent tutorial which seems to have a lot of positive comments.
To reproduce the error, just clone the repo on your machine (I use yarn, but this should work with npm too):
git clone https://github.com/sheljohn/minimal-semantic-react
cd minimal-semantic-react/
yarn install
yarn run serve
which opens at localhost:3000, and the error can be seen in the developer console.
As far as I understand, it seems that when React loads, it is looking to determine whether production or development mode is set, using the variable process.env.NODE_ENV, which is undefined in the browser.
This might be related to the target field in the Webpack config (set to web by default); but since React is loaded from CDN, prior to the bundle, I guess it doesn't know about what WebPack is doing, which makes me perplex as to why adding a plugin in the config would change anything...
Hence my question: is it possible to use semantic-ui-react by declaring the big libs (React, ReactDOM, semantic) as externals? Everything works fine if I bundle them, but the bundle ends up around 4MB, which is quite big.
Additional Details
Error as seen in Chrome (OSX High Sierra, v66.0.3359.181, dev console):
react.development.js:14 Uncaught ReferenceError: process is not defined
at react.development.js:14
(anonymous) # react.development.js:14
and code excerpt at line 14:
if (process.env.NODE_ENV !== "production") {
File webpack.config.js
const path = require("path");
const webpack = require("webpack");
const publicFolder = path.resolve(__dirname, "public");
module.exports = {
entry: "./src/index.jsx",
target: "web",
output: {
path: publicFolder,
filename: "bundle.js"
},
devServer: {
contentBase: publicFolder,
port: 3000
},
externals: {
'jquery': 'jQuery',
'lodash': '_',
'react': 'React',
'react-dom': 'ReactDOM',
'semantic-ui-react': 'semantic-ui-react'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
}
}),
new webpack.HotModuleReplacementPlugin()
]
};
File .babelrc
{
"presets": ["env", "react"]
}
I think I finally solved this:
Mistake #1: I was using cjs versions of the React libs from cdnjs, when I should have been using umd instead. Although UMD style is ugly, it seems to work fine within browsers, whereas CommonJS uses require for example. See this post for a comparison of AMD / CommonJS / UMD.
Mistake #2: in webpack.config.js, the "name" for the external semantic-ui-react should be semanticUIReact (case sensitive). This is what is defined in the window global when the script is loaded from the CDN (e.g. like jQuery or React).
I updated the repository with these fixes, and you should be able to reproduce that working example on your machine. This repository contains the bare minimum needed to get SemanticUI, React and Webpack working together. This would have saved me a lot of time, so hopefully other people get to benefit from that!
Everything works fine if I bundle them, but the bundle ends up around 4MB, which is quite big.
It's because you bundle them in "development" mode. Try using "production" in your script instead, it will be much smaller.
"build": "webpack --mode production"
If you bundle everything in production, without specifying external, it will be better for a standalone app.

How to use Babel without Webpack

I'm making an electron.js using React. I'm using JSX so need to use Babel to transpile. Many tutorials out there all suggests using Webpack.
Currently, I'm using Webpack 4. Here is my webpack.config.js
const path = require('path')
module.exports = {
entry: "./src/renderer.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "renderer.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
}
And my .babelrc
{
"presets": ["es2015", "stage-0", "react"]
}
Here I need to start with renderer.js because it contains most of my code and React components, the result is a bundled js file.
But all I want is to transpile all my jsx files to normal js files, something like transpile all JSX files within src to there according JS files in dist folders, and if available, watch and transpile when I edit the files. How to achieve that?
You can simply run babel through the command line:
babel --plugins transform-react-jsx-source script.js
Docs:
https://babeljs.io/docs/plugins/transform-react-jsx-source/
Note the three "Usages" on the page. All of them will get you what you want, none of them use webpack. The .babelrcfile can handle all your plugins/transforms and is the recommended usage. Then you just run babel
Here is an example from Material-UI's package.json:
"build:es2015": "cross-env NODE_ENV=production babel ./src --ignore *.spec.js --out-dir ./build",

localhost:8080 showing a blank page in react js

I have been following this tutorial to set up the environment for developing in react js.
React - tutorial
But when I run localhost:8080 on browser, it is showing a blank page.
I have tried all the browsers but none of them work.
I have installed webpack, but when I run webpack command, it says output file name not configured
My webpack-config.js file
module.exports = {
entry: './main.js',
output: {
path:'asd/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [ {
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
}
}
module.exports = config;
Also,in the tutorial they added a script index.js in the html file which the browser is not able to locate and shows the error
404:server could not locate the resource index.js
I start the server from the same path where my folder conatining all the files is located
Please help.
When you run webpack ,it will look the file index.js file in asd folder.please check your folder structure to verify there is a file named indexjs in asd folder.

Resources