Configuring Webpack for React - reactjs

I'm trying to create a Reactjs project from scratch. I've heard that it's easier to use create-react-app. I have also been told that the standard industry practise is to use webpack to bootstrap your React projects.
I have created my webpack config file like below:
const path = require('path');
const DIST_DIR = path.resolve(__dirname, "dist");
const SOURCE_DIR = path.resolve(__dirname, "src");
const config = {
entry: SOURCE_DIR + "/app/app.js",
output: {
path: DIST_DIR + '/app',
filename: 'bundle.js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: "/\.js?/",
include: SOURCE_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-2']
}
}
]
}
};
module.exports = config;
and I have added the build and build:prod scripts for running in devt and production mode as so:
{
"name": "basics",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
"build": "webpack -d && copy src/index.html dist/index.html &&
webpack-dev-server --content-base: src/ --inline --hot",
"build:prod": "webpack -p && copy src/index.html dist/index.html"
},
"keywords": [
"React",
"JavaScript",
"Front End"
],
"author": "MIT",
"license": "ISC",
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"#babel/preset-env": "^7.0.0-beta.40",
"#babel/preset-react": "^7.0.0-beta.40",
"#babel/preset-stage-2": "^7.0.0-beta.40",
"babel-loader": "^7.1.4",
"webpack": "^4.1.1",
"webpack-cli": "^2.0.10",
"webpack-dev-server": "^3.1.0"
}
}
When I run npm start, the app crashes and I get this error in console:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?,
exprContextRequest?, noParse?, rules?, defaultRules?,
unknownContextCritical?, unknownContextRecursive?,
unknownContextRegExp?, unknownContextRequest?, unsafeCache?,
wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?,
strictExportPresence?, strictThisContextOnImports? }
-> Options affecting the normal modules (`NormalModuleFactory`).
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! basics#1.0.0 build: `webpack -d && cp src/index.html
dist/index.html && webpack-dev-server --content-base: src/ --inline --hot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the basics#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.
I think the error is in my build script where I'm doing the copy but I can't be sure as it's my first time with webpack.
Can someone help me solve this? Thanks.

You want to use rules instead of loaders.
The information is there in the error. It tells you what are valid properties.
From the webpack docs https://webpack.js.org/concepts/loaders/
module.exports = {
module: {
rules: [
{ test: /\.css$/, use: 'css-loader' },
{ test: /\.ts$/, use: 'ts-loader' }
]
}
};
So for yours:
module: {
rules: [
{
test: "/\.js?/",
include: SOURCE_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-2']
}
}
]
}

Create-react-app is the easiest option but if you really want to understand how everything is set up under the hood you might want to build a simple app using Webpack, Babel and React from scratch. that's what I did.
Or you could go through my tutorial to save some time. Webpack, Babel, React, Redux, Apollo. From scratch to the production stack.

Related

Why can't I implement react Helmet into my project? [duplicate]

So I have been trying to setup React Js environment. I am facing the babel dependencies error. I know this problem is very common and there are tons of answers available but none of them have worked for me so far.
I have searched through the internet to solve it but it still shows the same error.
This is the error I am getting:
ERROR in ./main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module 'babel-preset-es2015' from 'D:\my-app'
at Function.module.exports [as sync] (D:\my-app\node_modules\resolve\lib\sync.js:58:15)
at resolveStandardizedName (D:\my-app\node_modules\#babel\core\lib\config\files\plugins.js:101:31)
at resolvePreset (D:\my-app\node_modules\#babel\core\lib\config\files\plugins.js:58:10)
at loadPreset (D:\my-app\node_modules\#babel\core\lib\config\files\plugins.js:77:20)
at createDescriptor (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:154:9)
at items.map (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:109:50)
at Array.map (<anonymous>)
at createDescriptors (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:109:29)
at createPresetDescriptors (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:101:10)
at passPerPreset (D:\my-app\node_modules\#babel\core\lib\config\config-descriptors.js:58:96)
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 448 bytes {0} [built]
[./node_modules/lodash/lodash.js] 527 KiB {0} [built]
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
[./node_modules/webpac
This is my .babelrc
{
"presets": ["es2015"]
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
},
"devDependencies": {
"#babel/core": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"#babel/preset-es2015": "^7.0.0-beta.53",
"babel-loader": "^8.0.6",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.31.0"
}
}
babel-loader#8.x uses Babel 7.x, which is #babel/core#^7.0.0, and more importantly in your case #babel/preset-env#7 replaces babel-preset-env#^1.7.0.
You'll need to make sure to do
npm install #babel/core #babel/preset-env
and update your Babel config to use #babel/preset-env instead of babel-preset-env with something like
"presets": [
"#babel/preset-env"
]
Note: For others coming across this, the issue may also be that you're using plugins/preset from Babel 6 on Babel 7. This may be hard to notice if you're using a third-party Babel preset since the versions of the presets may not match the version of Babel itself.
For NPM, run
npm install -D babel-loader #babel/core #babel/preset-env webpack
FOR YARN, run
yarn add --dev babel-loader #babel/core #babel/preset-env webpack
Late but might be helpful.
Downgrade the version of #babel-loader to version 7.
It worked for me when i encountered same problem
If you noticed this after installing a package like web3.
Kill the server and try to rebuild hope it helps

Error with Webpack: Invalid configuration object. Webpack has been initialised using a configuration object

I building an app with React.js and I'm using Babel and Webpack and packages. I was following this tutorial https://medium.com/#siddharthac6/getting-started-with-react-js-using-webpack-and-babel-66549f8fbcb8. I did everything by the instructions and when I compiles with npm start I get the following error:
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.entry['main'] should not contain the item '—' twice.
-> A non-empty array of non-empty strings
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sparo#1.0.0 start: webpack-dev-server — mode development — open — hot
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sparo#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users*****\AppData\Roaming\npm-cache_logs\2020-03-31T21_48_02_843Z-debug.log
this is the package.json file:
{
"name": "sparo",
"version": "1.0.0",
"description": "Sparo project",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server — mode development — open — hot",
"build": "webpack — mode production"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ringbearer-ramos14325/Sparo.git"
},
"author": "Daniel Ramos, Eric Brown II",
"license": "ISC",
"bugs": {
"url": "https://github.com/ringbearer-ramos14325/Sparo/issues"
},
"homepage": "https://github.com/ringbearer-ramos14325/Sparo#readme",
"dependencies": {
"create-react-app": "^3.4.1",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^4.0.3",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
}
and this is the webpack.config file:
const path = require("path");
const HWP = require("html-webpack-plugin");
module.exports = {
entry: path.join(__dirname, "/src/index.js"),
output: {
filename: "build.js",
path: path.join(__dirname, "/dist")
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}]
},
plugins: [
new HWP(
{template: path.join(__dirname, "/src/index.html")}
)
]
}

React npm start issue

I get this error when do npm start.
I tried deleting node modules and doing npm install again but dint fix issue
ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./main.js
Module not found: Error: Can't resolve 'babel' in '*****'
# multi (webpack)-dev-server/client?http://localhost:8080 ./main.js
webpack: Failed to compile
This is my webpack.config
module.exports = {
entry : './main.js',
output: {
path: '/',
filename: 'index.js'
},
devServer: {
inline: true,
port: 8083
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015','react']
}
}
]
}
}
This is my package.json
{
"name": "proj3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
}
}
you need to add Babel package to your project since it transpiles ES6 code (react).
This are the packages.
babel-loader
babel-core
babel-preset-es2015
babel-preset-react

Webpack + Babel: Couldn't find preset "es2015" relative to directory

I have a React project using Webpack and Babel. When I created it on an office computer, the Webpack ran fine. When I cloned the project onto my personal computer, it gave the following error:
ERROR in ./react_minesweeper.jsx
Module build failed: Error: Couldn't find preset "es2015" relative to directory "/Users/louisstephancruz/Desktop"
at /Users/louisstephancruz/Desktop/w6d5/minesweeper/node_modules/babel-core/lib/transformation/file/options/option-manager.js:298:19
at Array.map (native)
at OptionManager.resolvePresets (/Users/louisstephancruz/Desktop/w6d5/minesweeper/node_modules/babel-core/lib/transformation/file/options/option-manager.js:269:20)
Here's my webpack.config.js:
module.exports = {
entry: './react_minesweeper.jsx',
output: {
path: './',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: [/\.jsx?$/, /\.js?$/],
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['', '.js', '.jsx' ]
}
};
Here's my package.json:
{
"name": "minesweeper",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --inline"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.17.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.16.0",
"babel-preset-react": "^6.16.0",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.16.2"
},
"dependencies": {
"react": "^15.3.2",
"react-dom": "^15.3.2"
}
}
My version of node is: v5.6.0
My version of npm is: 3.6.0
npm i or npm install
should install all the packages in your package.json dependencies and dev dependencies (so long as your NODE_ENV environment variable does not equal production).
To check if you have a particular package installed you may do:
npm ls babel-preset-es2015
If for some reason your NODE_ENV is production and you would like to install dev dependencies you can use:
npm install --only=dev
Conversely, the following may be used on production machines that are dealing with already built code and do not need access to any development dependencies:
npm install --only=prod
I'd recommend creating a .babelrc in the root of your repo with the following content:
{ "presets": [ "es2015", "react" ] }
For the webpack config you may want to specify some other options:
{ context: __dirname
, resolve: { root: __dirname, extensions: [ '.js', '.jsx', '.json' ] }
}
in addition to the rest of your configuration, this tells webpack where the root directory of the bundling should take place from and what file extensions to treat as modules (which extensions you can omit in require / import statements).
I'd recommend checking out webpack's resolve.extensions for more information on that bit.
npm install babel-preset-es2015
does that help?
I resolved this issue when I removed .babelrc (hidden) file from "/Users/username" directory.
For me, I had to install the package globally.
npm install babel-preset-es2015 --save -g
npm install babel-preset-es2015 babel-preset-stage-2 --save
It's worked for me.

Webpack is looking for react in global directory

Here's my webpack-dev-server configuations
module.exports = {
entry: './main.js',
output: {
path: './',
filename: 'bundle.js'
},
devServer: {
inline: true,
port: 9000
},
module: {
loaders: [{
test: /\.js$/,
exclude: '/(node_modules)/',
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
}
};
Why would I get the following error when I run the server
ERROR in (webpack)-dev-server/~/strip-ansi/index.js
Module build failed: Error: Couldn't find preset "react" relative to directory "/Users/ecco/.nvm/versions/node/v5.4.0/lib/node_modules/webpack-dev-server/node_modules/strip-ansi"
my package.json
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"webpack": "^1.12.13"
}
You don't appear to have the webpack-dev-server installed as a local node module (it's not in your package.json
You can see which modules are installed locally and globally with npm list and npm list --global. To look for specific modules, pipe that command into grep i.e. npm list --global | grep webpack-dev-server
I'd suggest installing the dev server as a devDependency of your project. As a general rule, try to avoid installing modules with -g unless absolutely necessary. Also, use npm scripts (in your package.json) to run modules in your local directory, without having to reference them explicitly e.g.
{
"scripts": {
"serve": "webpack-dev-server --config your.config.js"
}
}
then run npm run serve rather than running ./node_modules/.bin/webpack-dev-server --config your.config.js (or worse, installing it globally)

Resources