So I was trying to set up the React/Babel/Webpack environment but I had some trouble doing so. I started creating a new folder, did the npm init and then I followed everything in this tutorial: https://facebook.github.io/react/docs/package-management.html
First, I've installed webpack globally
I've created a index.js with the same content on the tutorial
I've created a .babelrc file with { "presets": ["react"] }
Ran the npm install --save react react-dom babel-preset-react babel-loader babel-core
Then, when I run the command webpack main.js bundle.js --module-bind 'js=babel-loader' it gives me an error: "Module parse failed ~ You may need an appropriate loader to handle this file type.
Any idea guys? I've literally copy and pasted every step from the tutorial and I am sure all the files are correct. Thanks in advice!
Create file webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './main.js',
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/
}]
},
};
Run
webpack
and it will generate bundle.js for you.
Now make sure you have added index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
</head>
<body>
<div id="example"></div>
<script src="bundle.js"></script>
</body>
</html>
Looks like you accessing webpack from global. You might have installed webpack by doing
npm install -g webpack
Now,
Install webpack locally,
npm install webpack
and run.
./node_modules/webpack/bin/webpack.js main.js bundle.js --module-bind 'js=babel-loader'
Related
I have an old website running on server x. Now a React-App has been developed, which is on server y.
The website should display the React-App.
I have searched and read several posts on the topic but with no success so far.
The only solution currently working is an iframe but we don't want this.
If I do
npm run
and inspect the source on the server hosting the React-App, there is the following:
...
<div id="react-reporting"></div>
<script src="/static/js/bundle.js"></script><script src="/static/js/0.chunk.js"></script><script src="/static/js/main.chunk.js"></script>
Basically I would like to take this HTML-part and put it into the old site. Is this possible and if yes how?
My approach actually works, but I missed these two scripts:
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
So for testing locally it is:
<div id="react-reporting"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="http://localhost:3000/static/js/bundle.js"></script><script src="http://localhost:3000/static/js/0.chunk.js"></script>
<script src="http://localhost:3000/static/js/main.chunk.js"></script>
I also approached an error regarding sockjs which was caused by the test-file, which imports the React App, was being opened as file:// not via http://
Edit
After some more tests, I found using webpack is the best solution - it makes the app accessible as a single file.
package.json
...
"scripts": {
"start": "webpack-dev-server --inline --hot",
"build": "webpack --config webpack.config.js"
},
...
webpack.config.js
const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const glob = require("glob")
module.exports = {
entry: ['#babel/polyfill','./src/index.js'],
output: {
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
],
},
optimization: {
minimizer: [new UglifyJsPlugin()]
}
}
polyfill is needed for compatibility with IE11
every file processed (starting with the entries) counts as module. If it matches the "test"-part of a rule, the rule is applied (except for the excludes).
.babelrc
{
"presets": ['#babel/react',
['#babel/preset-env', {
"targets": {
"browsers": ["last 2 versions", "ie >= 11"]
}
}]],
"plugins": ['#babel/plugin-proposal-class-properties']
}
plugin-proposal-class-properties is only needed because I have some static members in classes.
When running
npm start
the Webpack-Dev-Server will start and make the app accessible under http://localhost:8080/dist/bundle.js.
Code to embed the app in another site:
<div id="react-reporting"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="http://localhost:8080/dist/bundle.js"></script>
If you are using create-react-app, go to the folder of your React App, and insert this command:
npm run build
This will generate a ./build folder with all that you need for your app.
Then it's simply a matter of dragging the ./build folder to server x.
You can also change the HTML that calls the react app so it will fit the old webpage.
i am learning reactjs. And i install my react app by
create-react-app first
but i want to know is there any manual way to install react app
I will write the shortest tutorial :)
Step1: Create folder and file structure like below:
Step2: Install dependencies below:
npm install -S react react-dom prop-types
Step3: Install dev dependencies:
npm install -D babel-core babel-loader babel-plugin-transform-class-properties babel-preset-es2015 babel-preset-react html-webpack-plugin webpack
Step4: Add index.html file to root folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!--Mounting point for React VDOM-->
<div id="root"></div>
</body>
</html>
Step5: Create webpack.config.js file in root folder with content:
let path = require('path'),
webpack = require('webpack'),
HtmlWebPackPlugin = require('html-webpack-plugin')
const PATHS = {
src: path.join(__dirname, 'src'),
dist: path.join(__dirname, 'dist'),
main: path.join(__dirname, 'src/main.js')
}
let wpConfig = {
entry: PATHS.main,
output: {
path: PATHS.dist,
filename: 'build.js',
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
"presets": [
"es2015",
"react"
],
"plugins": [
"transform-class-properties"
]
}
}
]
},
plugins: [
new HtmlWebPackPlugin({
title: 'My First React App',
template: './index.html'
})
]
}
module.exports = wpConfig
Step6: Add nmp command. In package.json file go to "scripts" sections and add build command like below:
"scripts": {
"build": "node_modules/.bin/webpack"
}
Step7: Create this simple React app file (main.js) in src folder:
import React from 'react'
import ReactDOM from 'react-dom'
const App = () => {
return (
<div>
<h1>Hello,</h1>
<p>This is my first react app!</p>
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
Step8: Run command:
npm run build
Webpack will build and save files(build.js and index.html) to dist folder. Open your /dist/index.html file in browser and your first react app from zero is ready! Start with this basic app, then add some additional features like stylesheets (css, sass), router, webpack dev-server, hot reloading and etc.Happy coding!
I see code online for a very simple react app like this:
index.html:
<!doctype html>
<html>
<head>
...
</head>
<body>
<div id="root"></div>
</body>
</html>
And then index.jsx:
import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
But how does the index.jsx javascript file even get run if there is no script tag in the index.html? Something similar to this: <script type="text/babel" src="./index.jsx">?
Expanding on my comment, this is an example of a webpack configuration you might use. This will auto generate an index.html file inside dist folder with the index_bundle.js embedded. HtmlWebpackPlugin has options you can pass, but as I said, this is a basic example.
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackConfig = {
entry: 'index.jsx',
output: {
path: 'dist',
filename: 'index_bundle.js'
},
module: {
loaders: {
test: /.jsx?$/,
loader: ['babel-loader'],
exclude: path.join(__dirname, 'node_modules'),
}
},
plugins: [new HtmlWebpackPlugin()]
};
Packages you'll need:
npm install --save-dev webpack babel-loader html-webpack-plugin
To use run webpack.
EDIT
You will also need a .babelrc file. Basic example:
{
"presets": {
"es5"
}
}
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/
I am about to move angular 1 + typescript project build setup from gulp to webpack, the only part I am stuck with is, how to bundle node_modules js file in proper sequence.
I was till now using bower for client side dependencies, and gulp has wiredep plugin which will look into bower dependencies section + main section to build the dependency order and get it to bundle it properly.
Now I understand that webpack philosophy is different, we should depend upload whatever is imported rather than any dependencies section as such.
so to get it to work I will need to do: move all dependencies from bower.json to package.json
currently as I am using typings, tsc considers the typings and gives me the output, I really don't need to write imports for bower packages as such.
So if i understand correctly, to get it work with webpack,
a) I should get away with typings and then directly import the js
files inside all my ts files??
As I understand, all the js modules from npm do work with modules, so does webpack really needs typings files?
OR
b) I should write a separate vendor.ts, where I should maintain the
sequence of imports (for js and css) myself,
but then that would be little painful to do (given I am used to wiredep handling it for me).
But then this will allow me bundle the vendor files separately using chunks-plugin
OR
c) is there any other standard way to handle this.
This is kinda pain point to move angular 1 from gulp to webpack.
When you import a module from a TypeScript file that's going to be loaded by webpack, it'll get it's content from node_modules and bundle it into the output file.
index.ts
import * as angular from "angular";
const myApp = angular.module("myApp", []);
myApp.controller("MyController", function PhoneListController($scope) {
$scope.phones = [
{
name: "Nexus S",
snippet: "Fast just got faster with Nexus S."
}, {
name: "Motorola XOOMâ„¢ with Wi-Fi",
snippet: "The Next, Next Generation tablet."
}, {
name: "MOTOROLA XOOMâ„¢",
snippet: "The Next, Next Generation tablet."
}
];
});
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
...
<script src="bundle.js"></script>
</head>
<body ng-controller="MyController">
<ul>
<li ng-repeat="phone in phones">
<span>{{phone.name}}</span>
<p>{{phone.snippet}}</p>
</li>
</ul>
</body>
</html>
webpack.config.js
module.exports = {
entry: "./index.ts",
output: {
filename: "./bundle.js"
},
devtool: "source-map",
resolve: {
extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: "ts-loader" }
],
preLoaders: [
{ test: /\.js$/, loader: "source-map-loader" }
]
}
};
Add angular, #types/angular, ts-loader, source-map-loader, typescript to your packages.json and run webpack.
It'll bundle everything inside a single file named bundle.js which will be used by your index.html.