I'm trying to use React.js on Ubuntu for a web dev project, but I can't figure out how to set it up. Please note that I am a beginner, and have only used Javascript with JQuery before. I tried to follow the instructions here, and I think I made it up to the point where I'm supposed to configure Babel. Here, in the terminal I ran
npm install --save-dev babel-cli babel-preset-react babel-preset-es2015
echo '{ "presets": ["react", "es2015"] }' > .babelrc
echo 'console.log([1, 2, 3].map(n => n + 1))' > index.js
./node_modules/.bin/babel index.js
The output I get is:
"use strict";
console.log([1, 2, 3].map(function (n) {
return n + 1;
}));
This is great and all, but I want to be able to run an html file with a corresponding .js file, as I would normally. As it is, when I write something like
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
with a corresponding html file, I just get console errors (Unexpected Token insert or something). Obviously, I haven't managed to install Ecmascript/JSX or whatever, and I don't really know what I'm doing.
So, I guess my question is, can anyone help me with a detailed explanation of how to get started? I just want to be able to write Javascript with React, and create a simple webpage. Thank you!
You dont need lots of stuff to start with React.
All you need to use react is include react and reactdom. Thats' it.
ReactDOM.render(
React.createElement('h1', {}, "Hi! This is the simplest way to get started with ReactJS"),
document.getElementById('only-react')
);
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>
<div id="only-react"></div>
These lines should get you started with just React without all the bloatware you will find in most of the tutorials.
Installing React
To install React with npm, run:
npm init
npm install --save react react-dom
Creating a Single Page Application
npm install -g create-react-app
create-react-app hello-world
cd hello-world
npm start
create-react-app
IMO, the best way to start a React project for a beginner is to use create-react-app. It is a zero config package that lets you jumpstart your React development. It contains necessary packages needed for react development.
npm install -g create-react-app
create-react-app react-app
cd react-app
npm start
React Environment Using webpack and Babel
If you don't want that and want to setup your own React project you could configure one with babel and webpack. I do recommend that you check this out to learn. Here's a tutorial.
For a beginner I'd recommend the first approach.
Your error come from here:
echo '{ "presets": ["react", "es2015"] }' > .babelrc
babel applies presets from right to left: it should transpile jsx first then the es2015 code.
The solution is to modify your .babelrc file by switching the order in the presets array like this:
{ "presets": ["es2015", "react"] }
Otherwise create-react-app is the best solution to begin without any configuration.
you have to install babel-cli globally so u can access babel command from anywhere. looks like you already installed babel-preset-react and babel-preset-env.
create a public folder and src folder. in public folder add index.html and index.js.
index.html
<body>
<div id="here"></div>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="./index.js"></script>
index.js should be empty. Whole point is to create a file that we change and we r going to have another file,index.js, that get generated or compiled by babel. index.js will be an auto-generated file.
In src folder we r gonna use react.jsx. create app.js in src folder. for the demonstration enter this simple code :
src/app.js
const template = <p>this is jsx</p>;
const appRoot = document.getElementById("here");
ReactDOM.render(template2, appRoot);
now run this command in terminal:
babel src/app.js --out-file=public/index.js --presets=env,react --watch
now check public/index.js. you should have this:
"use strict";
var template = React.createElement(
"p",
null,
"this is jsx"
);
var appRoot = document.getElementById("here");
ReactDOM.render(template2, appRoot);
Related
I'm pretty sure its my folders filepath for my compile Sass script, but I've been at this one a few hours now, so I'm hoping you can help... (maybe there's a setup setting IDK about?...
Two similar projects - 1 Vanilla, 1 React.
1. On both I have node, NPM and node-sass installed; via: npm i --save-dev node-sass
2. I've got livesass compiler going. On vanilla it works as expected. On the React project live-sass-compiler keeps on crashing (it is working long enough for me to test it though) and when i run in the terminal: npm run compile:sass the terminal turns into a node, never compiles, and also seems to get stuck in this state.
Please help!
NOW FOR THE DIFFERENCES:
==========Filepaths==========
(Filepath is indicated by "./", multiple files indicated by array syntax.
Vanilla (root):
index.html (stylesheet href="./STYLES/SCSS/index.css")
index.js
./STYLES/ [index.css, index.css.map, index.scss]
package.json (script: "compile:sass": "node-sass STYLES/SCSS/index.scss STYLES/output.css -w")
Works great!
REACT (root):
./public/index.html (stylesheet href="../src/STYLES/CSS/index.css")
./src/index.js
.src/STYLES/ [index.scss, (desired css output)]
package.json (script: "compile:sass": "node-sass src/STYLES/index.scss src/STYLES/CSS/index.css -w")
in both of them, inside the node-modules folder, I have installed:
"devDependencies": {"node-sass": "^7.0.1"}
Hey, I figured it out! - I got rid of live-sass-compiler (it's depreciated). - I also removed the "script: "compile:sass": "node-s..."" as it's no longer required. Compilation will happen natively every time you save the file.
TO USE WITH REACT:
Terminal:
npm install -D sass
sass —watch scss:css
1. add an .env file to the root. Inside type: “SASS_PATH=src/STYLES/SCSS”
(this allowed relative paths to be ignored on previous versions. I haven't gotten this to work but everything else seems to work. It may be depreciated... IDK.)
2. include the filepath import to the JS page you’d like the CSS to live under:
(example (for APP-WIDE Changes): index.js: import './STYLES/index.scss’ //imports to the app component
3. to import another file from index.scss:
Within the index.scss file:
#use './SCSS/_unorganized.scss'; // ("#import" will soon be depreciated, instead use #use)
Hope this saves someone else some time!
How do I get my react js app to start watching my sass files?
I did npm i sass vs npm i node-sass because I learned that node-sass is depreciated, I'm not sure if that has anything to do with automatic sass watching? (also, I have the latest version of node installed)
I know when you're not using a framework you have to type into the terminal " sass --watch input.scss output.css.", do I have to do the same in react js?
Also in my components I have imported the main.scss sheet!
this is the error I get when I try to run my react js app:
Failed to compile
./src/components/Login.js
Module not found: Can't resolve './scss/main.scss' in '/Users/karinapichardo/Desktop/login-project/src/components'
what am I missing to do? any help would be greatly appreciated
You are trying to import the SCSS file from the directory where Login.js is.
You should modify your import path to be like this:
import "../scss/main.scss"; // 2 dots at start of path
instead of like this:
import "./scss/main.scss";
Which will essentially navigate to the src directory before accessing the rest of the path
I try to create hello world applications by react js. I created the NodeJS application in IntelliJ IDEA. Create a helloworld.js file. and add this code to this file
import React from 'react';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
Added react-dom dependency to package.json. Made npm install command. Start Application
{
"name": "testjsapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react-dom": "^16.12.0"
}
}
Error:
"C:\Program Files\nodejs\node.exe" D:\projects\testjsapp\hello\helloworld.js
D:\projects\testjsapp\hello\helloworld.js:2
import React from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Module._compile (internal/modules/cjs/loader.js:891:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
Process finished with exit code 1
You're trying to execute a React program in Node.js, but it is designed to run in a web browser. There is no DOM in Node.js for you to manipulate. That just isn't going to work.
Since the program you are running uses JSX, you'll need to transpile it before it will work there too.
Go back to the tutorial. The section on setting up a local development environment provides an approach to getting up and running or you can look at a selection of toolchains that you can choose from.
check your current version
node -v
Update you node version to latest 13.X
Update nodejs
And Execute to create React App
npx create-react-app my-app
cd my-app
npm start
reference To create react app
and cross check it your existing Application, If needed
If you want neither using create-react-app nor settings up webpack and other tools, I can suggest starting with a simple HTML page that includes links to babel-standalone and required libraries, see https://reactjs.org/docs/add-react-to-a-website.html#quickly-try-jsx:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function Hello(props) {
const [name, setName] = React.useState(props.name);
return (
<h1 onClick = {() => setName(Math.random().toString(36).substring(5))}>
Hello {name}
</h1>
);
}
ReactDOM.render(
<Hello name='World'/>,
document.getElementById('root'),
);
</script>
</body>
</html>
Create an empty project, add a new HTML file, paste the content above in it, then right-click the file and choose either Run or Debug from its right-click menu to open application in browser
Well i came across same problem, i realized I wasn't doing something right.
First once you already create a react app using react-create-app
And you closed the project or run another project folder, if you want to start that project again
Make sure the folder path is correct then simply type
npm start in the terminal
that will solve the problem.
replace your line
import React from 'react';
with this one
const React = require("react")
I had this problem because I imported a Module from the client client to the server folder. Although the module was not used, it seems this kind of import is forbidden,
Already the Folder Called Src inside your Reactapp --> Goto that Src Directory and Replace App.js with your code then go back to ReactApp Directory and Run the code npm start ..It works for me..
For me, it worked when I passed an argument to transpile imports on the fly like below -
// transpile imports on the fly
require("#babel/register")({
ignore: [/(node_modules)/],
presets: ["#babel/preset-env", "#babel/preset-react"],
});
Also, I had a babel.config.js in the same folder as that of package.json for the server-side.
module.exports = {
presets: ["#babel/preset-env", "#babel/preset-react"],
plugins: [
"#babel/plugin-transform-runtime",
"#babel/plugin-transform-async-to-generator",
"#babel/transform-arrow-functions",
"#babel/proposal-object-rest-spread",
"#babel/proposal-class-properties",
],
};
I saw this issue when I wanted to debug my React app in IntelliJ which you do by running a JavaScript configuration in debug mode by e.g. right-click app.js > debug.
However, debugging doesn't work if your app isn't running already via npm start in terminal or right-click -> run on app.js.
So it's a two step process (in case of debugging), without step 1, syntax error message.
I am pretty new to vue.js - I only started using it today and naturally I have run into an error I cannot seem to resolve.
I am using the v-md-date-range-picker module:
(https://ly525.github.io/material-vue-daterange-picker/#quick-start.
The instructions tell me to do the following:
1
npm install --save v-md-date-range-picker
2
<template>
<v-md-date-range-picker></v-md-date-range-picker>
</template>
3
<script>
import Vue from 'vue';
import VMdDateRangePicker from "v-md-date-range-picker";
import "v-md-date-range-picker/dist/v-md-date-range-picker.css";
Vue.use(VMdDateRangePicker);
</script>
So, I ran the command in terminal in my project folder, added the 2 bit of code to my HelloWorld.vue page and then added the code from step 3 into the main.js.
When I have a look in my package.json file, I see:
"dependencies": {
"core-js": "^2.6.5",
"v-md-date-range-picker": "^2.6.0",
"vue": "^2.6.10"
},
However, I get the error:
Module not found: Error: Can't resolve 'v-md-date-range-picker/dist/v-md-date-range-picker.css' in '/Users/James/Documents/projects/vue-test/src'
am I missing something blatantly obvious here?
Edit:
I tried the response in the comments below which did not work.
On the main page of the module, I followed the instructions. However, going through the pages I found the same instructions with some extra text:
I assume that you have a working bundler setup e.g. generated by the vue-cli thats capable of loading SASS stylesheets and Vue.js SFC (Single File Components).
I am going to go out on a limb here and say I do not have a working bundler. I went into the node_modules folder, found that module and looked inside. There was no dist folder. Just .scss files etc..
So, I assume that I somehow need to build this project first.
How do I do that?
I thought running it in the browser would have done this on the fly but it clearly has not.
Edit 2:
After some googling around I found the command:
$ npm run build.
Which gives me this error:
This dependency is not found, To install it, you can run: npm install --save v-md-date-range-picker/dist/v-md-date-range-picker.css
So, I run that command and then I get the error:
Could not install from "v-md-date-range-picker/dist/v-md-date-range-picker.css" as it does not contain a package.json file.
Check if you can find this in the webpack.base.conf.js inside the build folder. If not add it.
module: {
rules: [
{
test: /\.css$/,
loader: ['style-loader', 'css-loader'], // Note that the order is very important
},
Run npm install style-loader css-loader --save before adding it to the file if it isn't there.
To Address your question
Run the command: npm install sass-loader --save
Then add an import for every SCSS file in the module.
This is not the most optimal solution, but that package looks broken to me and this is merely a workaround.
I will take time to try out the library myself and try to provide a fix for it.
Create v-md-date-range-picker.css in v-md-date-range-picker/dist/ and copy css from
md-date-range-picker.min.css
and refresh your page. For some reason css file is not being created when we install md-date-range-picker.min
I'm using Browserify to bundle a ReactJS application.
All my components include a require("react") at the top. This causes Browserify to include the ReactJS source in my bundle. But I'd like to exclude it.
How do I do that? Is this the right thing to do?
#NickTomlin gave this answer, but then deleted it.
You can use external:
browserify --external react src.js > dest.js
An example using the api:
var bundler = browserify('src.js');
bundler.external('react');
bundler.bundle();
This is a viable option. external requires another script to provide the module in a compatible way. You can produce such a script like this:
browserify -r react > react.js
env NODE_ENV=production browserify -r react | uglifyjs -m > react.min.js
And in HTML:
<script src="react.js"></script>
<script src="dest.js"></script>
dest.js is your code except react. react.js is just react and its dependencies.
Need more things external? Just add them in addition to react.
browserify -x react -x react-bootstrap src.js > dest.js
browserify -r react -r react-bootstrap > vendor.js
You could also do something like this in package.json
"browser": {"react": "./react-fake.js"}
// ./react-fake.js
try {
module.exports = require('react');
} catch(e){
module.exports = window.React;
}
And compile with -x react. This allows you to accept a -r react build, and fallback to a global React.
Sounds like you want to use browserify-shim.
In your package.json
"browserify-shim": {
"react": "global:React"
},
"browserify": {
"transform": [ "browserify-shim" ]
},
"dependencies": {
"browserify-shim": "~3.2.0"
}
(untested). This section has more information.
I also wanted to do this, and found a possible solution.
From the browserify -h help:
--ignore, -i Replace a file with an empty stub. Files can be globs.
Just use the ignore feature.
browserify -i react -i react-dom ...
I also added react and react-dom as peer dependencies, cause in my case, the package can be imported in other packages builds.
You can also use the externals section in the webpack.config.js file. eg:-
externals: {
// require('jquery') is loaded externally and avaliable as jQuery
"jquery": "jQuery"
}
See https://webpack.github.io/docs/library-and-externals.html