React Js Environment setup - javascript

I'm new to react js and I'm trying to set up the environment for it and I followed the steps mentioned in https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm.
But after doing all the things mentioned there I'm getting this error:
'webpack-dev-server' is not recognized as an internal or external command, operable program or batch file

If you want to develop an application using babel, webpack, etc. You need to follow following steps. No doubt there are much better tutorial available over the internet but it will give you some idea.
1.Webpack:
In browsers you can not require or import modules as you usually do while writing node.js code. With the help of a module bundler, maybe Webpack, you can write code that uses require/import in the same way that you would use it in node environment. I am assuming you will use webpack considering its popularity.
2. Install dependencies (es6)
These are minimal dependencies you need in your project (package.json) to get it working. You can directly copy paste the following text into a new file named "package.json". run the following set of commands in you EMPTY project directory:
install the node package manager
npm init [follow the command prompt to fill in meta data of your project like name, author,etc.]
install global packages
npm install -g babel babel-cli
[this will install transpiler(babel) into your global environment]
install module bundler
npm install webpack webpack-dev-server --save
install babel plugins
npm install babel-core babel-loader babel-preset-react babel-preset-es2015
After this command set, your package.json will start looking like as following:
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "No Command Written Yet"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
3.Write your webpack-config.js file
A sample webpack config file should like this. Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. Just remember the fact that
Webpack is a module bundler that bundles javascript and other assets for the browser.
var config = {
entry: './main.js',
output: {
path:'/',
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;
4.Set up entry point for your application
src->index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<App />
, document.querySelector('.init')
);
5.Setup index.html in your project root
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Welcome to ReactJs</title>
</head>
<body>
<div class="init"></div>
</body>
<script src="./public/bundle.js"></script>
</html>
6.Running
A slight change is needed in your package.json
replace:
"scripts": {
"test": "No Command Written Yet"
},
with
"scripts": {
"dev": "webpack-dev-server --hot"
},
[this will change the script you will run to execute the app bundled by webpack]
Now, whenever you want to run the project, just be in the project root directory and call:
npm run dev
DONE, Have Fun!

Run:
npm install webpack-dev-server --save-dev
And try again. You got the error because webpack-dev-server couldn't be found in your devDependencies inside of your package.json file

This is happening because you don't have webpack-dev-server installed as a global package, that's why you can execute directly.
The recommended way is installing it locally, in this way you'll avoid this problem.
Here you can find the steps to make it run.
Good luck

Related

Eslint with airbnb does not load when using .eslint.json

I'm trying to setup linting for a node project. I wish to use the airbnb style guide.
These are my dev dependencies in package.json:
"devDependencies": {
"eslint": "^8.2.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.25.2"
}
This is my .eslintrc.json file:
{
"env": {
"es2021": true,
"node": true
},
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"extends": "airbnb",
"rules": { /* ... */ }
}
I keep getting this error (in the VSCode Output terminal):
[Info - 9:24:00] Failed to load config "airbnb" to extend from. Referenced from: C:\GitWorkspace\lorand.eu\backend\.eslintrc.json
Note that eslint works just fine whenever using .yml or .js files as configuration.
How could I solve this error in the json config file?
P.S While this is a minimal reproducible error, the setup process that yielded the error came by following the instructions in this video:
https://www.youtube.com/watch?v=SydnKbGc7W8&t=1111s
When you use the eslint-config-airbnb-base package via the command below...
$ npm install --save-dev eslint-config-airbnb-base
...you have to add "airbnb-base" the following to your .eslintrc.json file's extends field, as seen below:
"extends": "airbnb-base"
The package eslint-config-airbnb that is installed via the command...
npm install --save-dev eslint-config-airbnb
...is the package that you use "extends": "airbnb" to your .eslintrc
file
The difference is that the latter, the airbnb supports react, where the airbnb-base does not.
Obviously, you don't want to add the unnecessary rules for a framework you're not using.

The CLI moved into a separate package: webpack-cli

I'm new to React.js and I'm trying to learn from the tutorials on tutorialspoint but I faced error. Here is the error on console when I execute npm start command:
C:\Users\HP\Desktop\reactApp1> npm start
> reactapp1#1.0.0 start C:\Users\HP\Desktop\reactApp1.
> webpack-dev-server --hot
The CLI moved into a separate package: webpack-cli.
Please install .webpack-cli. in addition to webpack itself to use the CLI.
-> When using npm: npm install webpack-cli -D
-> When using yarn: yarn add webpack-cli -D
module.js:540
throw err;
Error: Cannot find module .webpack-cli/bin/config-yargs.
at Function.Module._resolveFilenam (module.js:538:15)
at Function.Module. load (module.j5:668:25)
at Module.require (module.js,587.17)
at require (internal/module.js:11:18)
at Object•<anonymous> (C:\Users\HP\Desktop\reactApp1\node_modules\webpack-dev-server\bin\webpack-dev-server.js:65:1)
at Module. compile (module.js:663:30)
at Object.Module. extensions. .js (module.js:656:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:699:12)
at Function.Module. load (modul.js:691:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! reactapp#1.0.0 start: `webpack-dev-server --hot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the reactapp#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\HP\AppData\Roaming\npm-cache\_logs\2018-03-06T05_29_08_833Z-debug.log
package.json
{
"name": "reactapp1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"webpack": "^4.0.1",
"webpack-dev-server": "^3.1.0"
},
"devDependencies": {
"babel-loader": "^7.1.3"
}
}
webpack.config.js
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8090
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "index.js"></script>
</body>
</html>
I went through the same example and faced the same issue. So following the above answers I first ran this command -
npm install -g webpack-cli --save-dev
Nothing happened and was still facing the same issue.
Then I ran this command -
npm install webpack-cli --save-dev
The issue was solved but I was getting another error.
Turns out in the new Webpack version they have changed the module attributes also. So you need to make change in the webpack.config.js file also.
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
So basically loaders is replaced by rules inside the module object.
I made this change and it worked for me.
Hope it helps other people who are following this tutorial.
To resolve the Invalid configuration object issue, I referred to this answer.
https://stackoverflow.com/a/42482079/5892553
In webpack 3, webpack itself and the CLI for it used to be in the same package, but in version 4, they've separated the two to manage each of them better.
To solve your issue, install the webpack-cli package as the error suggests by running npm install webpack-cli --save-dev on the command line, same as you would any other package.
Was having the same problem, and no luck with the above solutions - I tried installing webpack-cli globally as well as locally and this worked.
npm install -g webpack-cli --save-dev
This fixed it for me. At least enough to perform webpack --mode development.
Step1: First run
npm i webpack webpack-dev-server webpack-cli --save-dev
Step2: Loaders are replaced with rules so change code in your webpack.config.j. Let's change your webpack.config.js file:
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8090
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
Step3: Now go to your package.json file and make some changes in your scripts option:
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
Step4: Now run
npm start
in console
Solved for Webpack 4 - I hope it works for webpack 2 onwards
Install webpack-cli globally too by using this command
npm i -g webpack-cli
So in total you need to run two following commands one for local and other for install CLI globally respectively.
npm i -D webpack-cli
npm i -g webpack-cli
it works for me I hope it will work for you too :)
I solved the problem with this.
npm i webpack-cli #webpack-cli/init
npx webpack-cli init
Hope to help 1
You need install webpack server, not webpack-cli. Have a look at the 2nd point in this blog post.
Try npm i -g webpack#2.2.1.
If you want to use webpack-dev-server, you need to install webpack and webpack-cli first. webpack is a module which store compiler and, webpack-cli is command-line-interface to run it. Otherwise, if you prefer webpack-command, a much more light-weight version of webpack-cli, you may need to install webpack and webpack-serve!
The error console is simply telling you how to resolve the issue. Seems like webpack module is dependent on webpack-cli module. To resolve the issue, just run the command npm install webpack-cli --save. it would just work fine.

How to create and publish a Vuejs component on NPM

I started working a lot with vue and started to use it in all the projects in the company where I work. And with that, I ended up creating some components, in general autocomplete, I know that there are many, I have already used some, but none have supplied all my needs. However, whenever I go to work on a new project and use the same component, either I recreates it, or I copy and paste it.
So I came to doubt How to create my component, upload to npmjs for whenever I use it, just give a npm install -save ..., and also be able to contribute a bit with the community.
update
With the release of vue-loader 15.x this answer will no longer work. Please use this instead https://medium.freecodecamp.org/how-to-create-a-vue-js-app-using-single-file-components-without-the-cli-7e73e5b8244f
Here is one way you can create/publish a Vuejs library/component from scratch.
As I am going to write down every step and command, make sure to follow the entire guide and you will be able to create and publish your own Vuejs component on NPM.
After you publish it, like most libraries you can install it using ex:
npm install --save your-component
And then import the component inside your app using
import something from 'your-component'
To start creating our first component, first create a folder called vuejs-hello-app (or any other name) and inside it, run:
npm init
Just hit enter until the interactive question ends and then npm will generate a file named package.json in that folder containing the following code.
(Note: I changed the description and version from 1.0.0 to 0.1.0 here is the result.)
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
After this, we'll need to install the dependencies for our library.
These dependencies are divided into two types: dependency and devDependency
dependency:
is the external library or libraries that our own component runs on. When someone installs your component, npm will make sure this dependency exists or gets installed first. Since we are creating a component for vue, we need to make sure vue is required. So, install it using:
npm install --save vue
devDependency:
is a bunch of libraries that we need only for development purposes. These libraries will help us build and/or transpile.
We install dev dependencies using the method above by adding the the suffix -dev to --save
Now, let us install the minimum dev dependencies we need for our component:
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env
npm install --save-dev cross-env
npm install --save-dev css-loader
npm install --save-dev file-loader
npm install --save-dev node-sass
npm install --save-dev sass-loader
npm install --save-dev vue-loader
npm install --save-dev vue-template-compiler
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
At this point the libraries will be installed and the package.json will be updated to look like following.
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"node-sass": "^4.7.2",
"sass-loader": "^6.0.6",
"vue-loader": "^13.5.0",
"vue-template-compiler": "^2.5.9",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"vue": "^2.5.9"
}
}
(note: I have added "build": "webpack -p" to build our lib with webpack)
Now, since our code needs to be built and transpiled, we need a folder to store the build version. Go ahead and create a folder inside our root folder and call it: dist and in the same place a configuration file for webpack and name it webpack.config.js
All of the files we have so far created are for configuring and stuff. For the actual app that people are going to use, we need to create at least two files inside our src/ directory.
A main.js and VuejsHelloApp.vue put them as:
./src/main.js and ./src/components/VuejsHelloApp.vue
I have mine structured like this:
dist
node_modules
src
main.js
components
VuejsHelloApp.vue
.babelrc
.eslintignore
.gitignore
.npmignore
.travis.yml
CONTRIBUTING
LICENSE
package.json
README.md
webpack.config.js
I will just go through the files listed and describe what each file does in-case anyone is curious:
/dist is where a build (transpiled), minified, non-ES6 version of your code will be stores
node_modules I think we know this already, let's ignore it
src/ this is root dir of your library.
.babelrc is where your babel options are kept, so add this to disable presets on modules
{
"presets": [
[
"env",
{
"modules": false
}
]
]
}
.eslintignore This is where you tell ESLINT to ignore linting so put this inside:
build/*.js
.gitignore
add files you want to ignore (from git)
.npmignore same as .gitignore for NPM
.travis.yml if you need CI check examples from travis and configure it
CONTRIBUTING not required
LICENSE not required
package.json ignore for now
README.md not required
webpack.config.js This is the important file that let's you create a build, browser compatible version of your code.
So, according to our app, here is a minimal example of what it should look like:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
module: {
rules: [
// use babel-loader for js files
{ test: /\.js$/, use: 'babel-loader' },
// use vue-loader for .vue files
{ test: /\.vue$/, use: 'vue-loader' }
]
},
// default for pretty much every project
context: __dirname,
// specify your entry/main file
output: {
// specify your output directory...
path: path.resolve(__dirname, './dist'),
// and filename
filename: 'vuejs-hello-app.js'
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Note that the important directives here are entry and output. You can check webpack docs to learn more if you want to fully customize your app.
But basically, we're telling webpack to get the ./src/main.js (our app) and output it as ./dist/vuejs-hello-app.js
Now, we are almost finished setting up everything except the actual app.
Go to /src/components/VuejsHelloApp.vue and dump this simple app, which will move a button right or left when you hover on it
<template>
<div>
<button #mouseover='move($event)'> I'm alive </button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
move (event) {
let pos = event.target.style.float;
if(pos === 'left'){
event.target.style.float = 'right'
}else{
event.target.style.float = 'left'
}
}
}
}
</script>
<style scoped>
</style>
And not but not least, got to ./src/main.js and export your app like:
import VuejsHelloApp from './components/VuejsHelloApp.vue'
export default VuejsHelloApp
Now go to your package.json file replace the "main: "index.js", with "main": "src/main.js",
After this, simply run these commands to build and publish your app:
npm run build
git add .
git commit -m "initial commit"
git push -u origin master
npm login
npm publish
Importing and using the library.
If everything went smoothly, then simply install your app like this:
npm install --save vuejs-hello-app
And use it in vue like this:
<template>
<div>
<VuejsHelloApp> </VuejsHelloApp>
</div>
</template>
<script>
import VuejsHelloApp from 'vuejs-hello-app'
export default {
name: 'HelloWorld',
components: { VuejsHelloApp }
}
</script>
I made this app https://github.com/samayo/vuejs-hello-app while writing the answer, it might help to better understand the code

How to use babel with npm package that will be used by react

Trying to do what I thought was a simple thing.
I have a node package that uses advanced js syntax. I want to depend on it in a react project.
So I installed babel packages via --save-dev, and added a .babelrc:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread"]
}
That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:
{
"name": "bla",
"version": "1.0.0",
"scripts": {
"postinstall": "babel src --out-dir lib"
},
"main": "lib/index.js",
"dependencies": {},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react-native": "^4.0.0"
}
}
When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.
Why is this so difficult? What am I doing wrong?
sh: 1: babel: not found is from your shell not finding the babel binary file (normally under ./node_modules/.bin/babel)
You'd want to compile before you publish to npm, so anyone who installs your package has the built files. But, for Github try something like:
"postinstall": "npx babel src --out-dir lib"
This hack worked instead of the postinstall:
...
"preinstall": "npm install --ignore-scripts && babel src --out-dir lib",
...
Source: https://github.com/Financial-Times/structured-google-docs-client/commit/891180db742ed00cace0139b201850f79d337098
Also relevant: https://github.com/npm/npm/issues/10366
I am not sure I understand the need here correctly, but could you not just run the babel call in prepare or prepublish scripts? That way only local npm install calls would pick that up.
See more about npm scripts lifecycle: https://docs.npmjs.com/misc/scripts

Webpack with html-webpack-plugin, error when installed globally

I know this problem has been reported elsewhere, when webpack and html-webpack-plugin are installed with npm -g:
module.js:341
throw err;
^
Error: Cannot find module 'html-webpack-plugin'
at Function.Module._resolveFilename (module.js:339:15)
And the answer people have found is to install one or both locally to the project. But that won't work for me. I need to get this working in our shared build system, not just in my dev environment. This means having it installed globally so that all projects have access to it via their ant/nant build scripts run by Jenkins.
My project is very simple. A couple of html pages with content generated by reactJS scripts included in the html with script tags. This should be easy, and its beginning to be a pain. Thinking of dumping webpack and looking for another simple javascript package manager.
Are there environment variables that we can use to tell webpack to look in the global node 'node_modules' directory for 'require'd plugings/packages?
Suggestions?
You don't have to install webpack globally for Jenkins.
Add to your package.json under scripts a command that runs the local webpack, like this:
"scripts": {
"start": "webpack-dev-server --inline --hot",
"build": "webpack -p"
},
Now Jenkins can run your build script, without having a global webpack installed:
npm run build
In this way you can maintain multiple projects with different versions of webpack, and each project can have it's own local dependencies.
The scripts prop is part of the projects package.json. The package.json contains all dependencies, and dev dependencies (build, testing, etc...) of the project. Using the package.json running NPM install on your build machine, you can install locally (part of the project dir) all dependencies. A sample of a package.json for an angular project built with webpack:
{
"name": "whatever",
"version": "1.2.0",
"description": "whatever",
"scripts": {
"start": "webpack-dev-server --inline --hot", // runs the dev server
"build": "webpack -p" // builds the release
},
"dependencies": { // the dependencies that are part of the actual release
"angular": "1.5.0",
"angular-animate": "1.5.0",
"angular-messages": "1.5.0",
"angular-ui-router": "0.2.15"
},
"devDependencies": { // build dependencies
"babel-core": "6.5.2",
"babel-eslint": "6.0.0-beta.1",
"babel-loader": "6.2.3",
"babel-preset-es2015": "6.5.0",
"babel-preset-stage-0": "6.5.0",
"css-loader": "0.23.1",
"file-loader": "0.8.5",
"html-loader": "0.4.3",
"html-webpack-plugin": "2.14.0",
"less-loader": "2.2.2",
"style-loader": "0.13.0",
"url-loader": "0.5.7",
"webpack": "1.12.14",
"webpack-dev-server": "1.14.1"
},
"license": "MIT"
}
Whenever the git master is updated, Jenkins pulls the latest commit, cleans the current build directory, including all dependencies, and runs in the project folder the following commands:
npm install to install all dependencies locally, as part of the project folder
npm run build to build the release
Jenkins is not aware of webpack or any other build tool or dependency. The only things that are installed globally on Jenkins are nodejs and npm.
And here is the simple bash script that runs the commands:
rm -rf node_modules || true // remove node_modules (all deps)
npm install // install all deps
npm run build // run the build script

Categories