How to install React on this project - reactjs

I got this starting point app that was given to me, and I have to add react to it.
Its a basic node application with this sctructure:
MyProject
src
scripts
index.js
styles
index.scss
index.html
webpack
webpack.common.js
webpack.config.dev.js
webpack.config.prod.js
.babelrc
And I also got this package.json:
{
"name": "frontend-assessment-test",
"version": "1.0.0",
"description": "A frontend assessment test for our new pirates, which are willing to come on board.",
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config webpack/webpack.config.prod.js --colors",
"start": "webpack-dev-server --open --config webpack/webpack.config.dev.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holidaypirates/frontend-assessment-test"
},
"author": "HolidayPirates",
"license": "MIT",
"bugs": {
"url": "https://github.com/holidaypirates/frontend-assessment-test/issues"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.6.3",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.4",
"cross-env": "^6.0.3",
"css-loader": "^3.2.0",
"eslint": "^6.5.1",
"eslint-loader": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^4.0.0-beta.8",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.13.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.9.0",
"webpack-merge": "^4.2.2"
},
"dependencies": {
"#babel/polyfill": "^7.6.0",
"core-js": "^3.3.3"
}
}
The babel file webpack.common.js has this configuration:
module.exports = {
entry: {
app: Path.resolve(__dirname, '../src/scripts/index.js')
},
output: {
path: Path.join(__dirname, '../build'),
filename: 'js/[name].js'
},
optimization: {
splitChunks: {
chunks: 'all',
name: false
}
},
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin([
{ from: Path.resolve(__dirname, '../public'), to: 'public' }
]),
new HtmlWebpackPlugin({
template: Path.resolve(__dirname, '../src/index.html')
})
],
resolve: {
alias: {
'~': Path.resolve(__dirname, '../src')
}
},
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto'
},
{
test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
},
]
}
};
So because I saw threre is babel and style loader added to the webpack, if I would just install react and react-dom I could then start using react, if I would, in the index.js file import react and try to render a basic component.
But i get an error that Module build failed (from ./node_modules/babel-loader/lib/index.js):
Any idea what should I change in webpack config or which other package other than react
and react-dom in order to use react in index.js?
Thanks.

This code base will not support react js. Babel is used to converted the non understandable JS parts(mostly es6 or more) to es5. Simple babel configuration will not work in your case, every library has their own way of syntax.
For example, in order to use the react you should be installing babel-preset-react which is mandatory for react.
The above mentioned will understand the jsx and react functionalities and converts to es5.

Install react first, see the hello world is working then try to add your node.js project into that react, try to add small chunk continuously and see the result
My personal opinion if possible, keep UI(react) and backend(node) separate

Related

Package issues with babel

Community, just started with React and I've created the simplest stuff ever. Does it work? Of course... not.
I've been googling and tried to make those adjustments described. But still, my killer application won't run and I seem to end up with two different error messages depending on the actions i take:
"Babel Plugin/Preset files are not allowed to export objects, only functions"
"Uncaught ReferenceError: process is not defined"
I honestly don't know how to proceed, I've tried to upgrade to the latest "#babel/...", tried to downgrade to earlier babel versions, but React is playing hide and seek with me.
// app.js
import React from 'react';
import ReactDOM from 'react-dom';
const text = <p>Hello world</p>
ReactDOM.render(text, document.getElementById('app'));
// babel.rc
{
"presets": [
"env",
"react"
]
}
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
mode: 'none',
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}]
}
};
// package.json
{
"name": "killer-app",
"version": "1.0.0",
"main": "index.js",
"author": "",
"license": "",
"scripts": {
"serve": "live-server public/",
"build": "webpack --watch",
"build-babel": "babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch"
},
"dependencies": {
"babel-cli": "^6.26.0",
"babel-core": "6.25.0",
"babel-loader": "7.1.1",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"live-server": "^1.2.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"validator": "^13.7.0",
"webpack": "^5.73.0"
},
"devDependencies": {
"webpack-cli": "^4.10.0"
}
}
As a side-note, the script "yarn run build-babel" doesn't work either. This script worked before I installed Webpack.
Any advice is appreciated! :)

Vaadin into Angular v1.x with through Webpack bundle

I am trying to bundle Vaadin in a single file to be loaded inside my portal (which running with AngularJS V1.x) following this guide. It fails because is using an old configuration (which I fixed for the development mode but I didn't for the production one) and because I could bundle the references left in the node modules instead of copied inside the bundle.
So I tried with a new webpack setup with this configuration:
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
var config = {
// TODO: Add common Configuration
mode: 'development',
performance: {
hints: false,
maxEntrypointSize: 5512000,
maxAssetSize: 5512000
},
devServer: {
contentBase: './dist',
},
module: {}
};
var jsConfig = Object.assign({}, config, {
entry: {
index: './src/index.js',
vaadin: './src/webcomponentsjs/main.js'
},
optimization: {
minimize: true
},
plugins: [
new HtmlWebpackPlugin({
title: 'Vaadin Library',
template: './src/index.html'
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: false
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: ['transform-class-properties']
}
}
}
],
}
});
module.exports = [
jsConfig
];
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": true,
"dependencies": {
"lodash": "^4.17.21",
"web-animations-js": "^2.3.2"
},
"devDependencies": {
"#babel/cli": "^7.14.5",
"#babel/core": "^7.14.6",
"#babel/plugin-syntax-top-level-await": "^7.14.5",
"#babel/plugin-transform-template-literals": "^7.14.5",
"#babel/preset-env": "^7.14.5",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^8.2.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"css-loader": "^5.2.6",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^5.3.1",
"install": "^0.13.0",
"mini-css-extract-plugin": "^1.6.0",
"npm": "^7.17.0",
"sass": "^1.35.1",
"sass-loader": "^12.1.0",
"script-ext-html-webpack-plugin": "^2.1.5",
"style-loader": "^2.0.0",
"url-loader": "^4.1.1",
"webpack": "^5.39.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "echo \"Bundling Vaadin library to less files and convert to ES5 with Webpack and Babel (loader)\" && webpack",
"start": "webpack serve --open"
},
"keywords": [],
"author": "",
"license": "ISC"
}
And here the errors (for each component imported in index.js):
ERROR in ./src/index.js 2:0-31
Module not found: Error: Can't resolve '#vaadin/vaadin-button' in '/Users/username/Dev/current/webpack-vaadin/src'
Did you mean './#vaadin/vaadin-button'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.
Did anyone already manage to import Vaadin into an angularJs application? How did you do or could you point me at the right place in the documentation (which I didn't find as very new with this FW)?
Thanks in advance.

several instance of styled-component in node modules

I am creating a separate repo for sharable UI component. I am using styled-component. When I am locally publishing the package using npm link. It's throwing error.
Error is explained here.
Project
|
+-- node_modules
|
+-- styled-component v4.0.2
|
+-- ui-component
|
+-- styled-component v4.1.1
There are couple of ways to fix it as if mention in link.
npm dedupe (Not suitable for dev environment as it's not work well with npm link ).
Setting up your webpack (some of the project will be using create-react-app so they don't have access to webpack).
I have two though running in my mind.
First, both the solution kind of forcing end user to do something at your end. I want to make it like other npm package where you just install and use it without telling user to do something in configuration level.
Second, Why I have to even do that. I have setup everything in webpack. I have ask webpack to not to use it's own dependency for the particular package rather use the end user package.
How other npm packages are working which depends on parent dependency but they use own dependancy in dev process. like react
Here is files from my sharable UI component library.
Package.json
{
"name": "ui-component",
"version": "1.0.0",
"description": "Shareable web UI component",
"main": "build/index.js",
"scripts": {
"dev": "start-storybook -p 6006",
"build": "webpack",
"build:storybook": "build-storybook",
"test": "jest --env=jsdom",
"lint": "eslint"
},
"jest": {
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
},
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!storybook-static/**/*.{js,jsx}",
"!congif/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/src/enzymeSetup.js"
],
"testMatch": [
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"testPathIgnorePatterns": [
"<rootDir>/__tests__/setup/"
],
"moduleNameMapper": {
"^#theme": "<rootDir>/src/theme.js",
"^#validation": "<rootDir>/src/validation/index.js",
"^#helper": "<rootDir>/src/helper.js"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": [
"npm run lint --fix",
"cross-env CI=true npm test -- --coverage --bail --findRelatedTests"
]
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#material-ui/core": "^3.5.1",
"#material-ui/icons": "^3.0.1",
"react": "^16.6.3",
"react-router-dom": "^4.3.1",
"styled-components": "^4.1.1"
},
"devDependencies": {
"#babel/core": "^7.1.6",
"babel-core": "7.0.0-bridge.0",
"#babel/preset-env": "^7.1.6",
"#babel/preset-react": "^7.0.0",
"#storybook/addon-actions": "^4.0.7",
"#storybook/addon-centered": "^4.0.7",
"#storybook/addon-info": "^4.0.7",
"#storybook/addon-links": "^4.0.7",
"#storybook/addon-options": "^4.0.7",
"#storybook/addons": "^4.0.7",
"#storybook/components": "^4.0.7",
"#storybook/react": "^4.0.7",
"babel-eslint": "^9.0.0",
"babel-jest": "^23.6.0",
"babel-loader": "^8.0.4",
"css-loader": "^1.0.1",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.6.0",
"eslint": "^5.9.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-react": "^7.11.1",
"file-loader": "^2.0.0",
"husky": "^1.1.2",
"jest": "^23.6.0",
"lint-staged": "^8.0.4",
"react-dom": "^16.6.3",
"react-router-dom": "^4.3.1",
"storybook-styled-components": "^1.1.2",
"style-loader": "^0.23.1",
"webpack": "^4.26.0",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
},
"peerDependencies": {
"react": "^16.5.2",
"styled-components": "^4.1.1"
}
}
webpack
const path = require ('path');
module.exports = {
entry: {
main: './src/index.js',
},
output: {
path: path.resolve(__dirname, './build'),
filename: 'index.js',
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
}],
}
],
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all',
}
}
}
},
plugins: [],
resolve: {
alias: {
'#theme': path.resolve(__dirname, './src/theme.js'),
'#validation': path.resolve(__dirname, './src/validation/index.js'),
'#helper': path.resolve(__dirname, './src/helper.js'),
}
},
externals: {
'react': 'commonjs react', // this line is just to use the React dependency of our parent-testing-project instead of using our own React.
'styled-components': 'commonjs styled-components' // this line is just to use the React dependency of our parent-testing-project instead of using our own styled-component.
}
}
My parent app is using styled-components ^4.0.2 and my sharable ui library using styled-components "styled-components": "^4.1.1".
I have had a entries in peerDependencies as well as in webpack. struggling with it more than a day any help would highly appreciated.
See this FAQ entry in the official styled-components documentation. In most cases, adding an alias to the webpack configuration is enough to overcome the issue:
resolve: {
+ alias: {
+ "styled-components": path.resolve("./node_modules", "styled-components"),
+ }
}
I spent hours trying various things to overcome this issue myself, including everything in the styled-components docs with no luck at all. Nothing worked until I found this suggestion on GitHub.
Adding the below to your Webpack config tells it to use a single runtime for all of your entrypoints, instead of creating a new runtime for each.
optimization: {
runtimeChunk: {
name: "vendor"
},
....
I also run into this issue, somehow I think you can't load two version of styled-components sometimes even when they are the same version, ex. 4.4.1.
So in the end, i have to use peerDependencies, luckily i have control on all the repos, so I relocated the styled-components to peerDependencies for my core libraries. And then rely on only one copy in the implementation repo.
I can still smell things not right here, but so far i can only get the ThemeProvider to work this way across different repos.

React Build Tool and Dev Server

Need some direction in terms of setting up the DEV environment and server for a project I'm starting for learning purposes. I want to use ReacJS with Bootstrap. Last time I worked with ReactJS, the build and server was already configured and I did not have to do much. We were using npm, gulp and bunch of other stuff.
Now that I'm trying to set this up, I'm not sure what to do. Can someone outline the simplest steps I can follow. I want to use latest versions of React eco-system and ideally have a build system to minify and combine files and stuff. There is so much info on Google that it is confusing. Another challenge I'm facing is that which versions to specify in package.json. Instead of gulp I decided to use webpack. Wasn't really sure if to go with gulp or webpack but decided to go with webpack. It is all working but not sure if I have the most updated versions of everything or need more stuff. I know for sure I don't have any watchers to auto refresh page on changes. For server I'm just using npm, not sure if that is all I need or there are any advantages of using others.
This is my package.json
{
"name": "track",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --port 3000 --progress --inline",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"html-webpack-plugin": "^2.29.0",
"path": "^0.12.7",
"react": "^16.0.0",
"react-dom": "^15.6.1",
"webpack": "^3.0.0",
"webpack-dev-server": "^2.5.0"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.0",
"babel-preset-es2017": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
Below is the webpack.config.js
module.exports = {
entry: './src/app.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: { presets: [ 'es2015', 'react' ] }
}
]
}
};
Can someone outline the simplest steps I can follow.
I have faced very similar situation but i was working with react, redux, react-redux, other libraries and using axios for sending (http) request where i have to figure out by myself , Here's what i did :
NOTE: Make sure you have Node.js installed because i have Node along with webpack-dev-server here
npm init
Installed project dependencies using npm.
Inside script i have given link to node and webpack-dev-server as you can see
package.json
{
"name": "searchapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.3"
},
"dependencies": {
"babel-preset-stage-1": "^6.24.1",
"lodash": "^4.17.4",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
"redux": "^3.7.2",
"redux-promise": "^0.5.3"
}
}
And this is webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
bundle: './src/index.js',
},
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
And then make sure to include .babelrc
{
"presets": ["react", "es2015", "stage-1"]
}
And if you have github repository make sure to include .gitignore file so that these folders or files will not be included in git repo
.gitignore
/node_modules
bundle.js
npm-debug.log
.DS_Store
If you think all of this is overwhelming and too much for a start then best place to start with is create-react-app

Why do we need to use import 'babel-polyfill'; in react components?

I wonder if we user babel loader + all the presets, why do we need to include babel-polyfill anyway into our components? I just think that babel-loader should do all the job itself.
Examples were taken here https://github.com/reactjs/redux/tree/master/examples
What i am asking about is:
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import App from './containers/App';
Here is package example:
{
"name": "redux-shopping-cart-example",
"version": "0.0.0",
"description": "Redux shopping-cart example",
"scripts": {
"start": "node server.js",
"test": "cross-env NODE_ENV=test mocha --recursive --compilers js:babel-register",
"test:watch": "npm test -- --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/reactjs/redux.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/reactjs/redux/issues"
},
"homepage": "http://redux.js.org",
"dependencies": {
"babel-polyfill": "^6.3.14",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-redux": "^4.2.1",
"redux": "^3.2.1",
"redux-thunk": "^1.0.3"
},
"devDependencies": {
"babel-core": "^6.3.15",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-react-hmre": "^1.1.1",
"cross-env": "^1.0.7",
"enzyme": "^2.0.0",
"express": "^4.13.3",
"json-loader": "^0.5.3",
"react-addons-test-utils": "^0.14.7",
"redux-logger": "^2.0.1",
"mocha": "^2.2.5",
"node-libs-browser": "^0.5.2",
"webpack": "^1.9.11",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.9.1"
}
}
Here is webpack config example taken from https://github.com/reactjs/redux/tree/master/examples
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
loaders: [ 'babel?presets[]=react,presets[]=es2015,presets[]=react-hmre' ],
exclude: /node_modules/,
include: __dirname
},
{
test: /\.json$/,
loaders: [ 'json' ],
exclude: /node_modules/,
include: __dirname
}
]
}
}
Babel transpiles your code to something that browsers can understand, but the resulting code uses features that may or may not work in every single browser. For example Object.assign is not supported in all browsers, so babel-polyfill fills the holes. It's just a collection of polyfills that you would usually include anyway to have support for legacy browsers.
Consider this code:
const foo = {
name: 'Homer'
};
const bar = Object.assign({}, foo, {age: '?'});
console.log(Object.keys(foo), Object.keys(bar));
Babel will transpile this to the almost identical:
'use strict';
var foo = {
name: 'Homer'
};
var bar = Object.assign({}, foo, { age: '?' });
console.log(Object.keys(foo), Object.keys(bar));
because this is normal old school JS syntax. However, that doesn't mean that the native functions used are implemented in all browsers, so we need to include the polyfill.

Resources