ReactJS App on PHP backend - how to hot reload on local machine? - reactjs

I am developing a ReactJS-App that gets served by a PHP backend. On my local machine I set up MAMP with a virtual host pointing to my project's root and I use webpack to bundle my React-App.
Since I really enjoy working with hot reloading I now try to use the webpack dev server to proxy MAMP and benfit from its react hot loading capabilities.
I haven't been able to get it working yet and I hope for someone to help me with the configuration. Or isn't my approach basically working? Anyway, I'll be happy if you help me out with this. Thanks in advance! Here's my webpack config so far:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
module.exports = {
devtool: 'cheap-module-source-map',
devServer: {
port: 3000,
proxy: {
'*': {
target: 'http://my-virtual-host.dev:8888/',
}
}
},
entry: [
'./src/app.jsx'
],
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: 'http://localhost:3000/build/'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
loaders: [
{
enforce: 'pre',
test: /\.jsx?$/,
include: [
path.resolve(__dirname, 'src'),
],
loader: 'eslint-loader',
},
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, 'src'),
],
loader: 'react-hot-loader'
},
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, 'src'),
],
loader: 'babel-loader',
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
options: { importLoaders: 1 },
},
'postcss-loader',
],
}),
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new ExtractTextPlugin('bundle.css'),
new StyleLintPlugin({
configFile: '.stylelintrc',
context: 'src',
files: '**/*.pcss'
})
]
};

Okay, I found the solution! My fault: I was thinking that my webpack dev server should "proxy" every request to MAMP and return its response. Putting in the other way around solved my Problem: MAMP serves my PHP Application and the webpack dev server only its assets.
When in development mode my PHP Application links assets to the webpack dev server (this discussion around a github issue helped me a lot: https://github.com/webpack/webpack-dev-server/issues/400).
Now, the main attributes I changed in my webpack config are:
module.exports = {
devServer: {
proxy: {
'*': {
target: 'http://my-virtual-host.dev:8888/',
changeOrigin: true,
}
}
},
entry: [
'webpack-dev-server/client?http://localhost:8080/',
'webpack/hot/only-dev-server', // Enable hot reloading
'./src/app.jsx'
],
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: 'http://localhost:8080/build/'
},
}
Linking assets for example to http://localhost:8080/build/app.js, the proxy settings and the output.publicPath did the trick. Hot reloading works fine.
Although it works for me now I'm still interessted in your thoughts!

Related

Why does %PUBLIC_URL% not get replaced in Webpack bundled index.html?

I am trying to deploy the front-end of my web application, but when I deploy to my hosting platform (currently AWS Amplify/S3) - no content displays on the website
I created the application using create-react-app, so the project structure follows their standard (public, src folders etc.).
When I run the application locally it works fine.
From the console errors, and looking at the index.html page that is generated by webpack, it looks like it is not replacing the %PUBLIC_URL% field that should be replaced with the public directory on build.
Please can someone explain how to fix this issue?
I have included my webpack.config file below and the full repo can be found here
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const config = {
entry: ['react-hot-loader/patch', './src/index.js'],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.svg$/,
use: 'file-loader',
},
{
test: /\.png$/,
use: [
{
loader: 'url-loader',
options: {
mimetype: 'image/png',
},
},
],
},
{
test: /\.(ttf|eot|woff|woff2)$/,
use: 'file-loader',
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'react-dom': '#hot-loader/react-dom',
},
},
devServer: {
contentBase: './build',
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve('./public/index.html'),
}),
],
}
module.exports = config
Turns out this was an issue with me trying to add a custom Webpack configuration to a create-react-app project.
I've removed the Webpack config now, and instead used the dist files created when using the create-react-app build process.

Script1014 Invalid character error in IE11

When I'm trying to open my react project in IE11, I get the error 'SCRIPT1014 Invalid Character'.
And every other browser works perfectly even the Edge.
I have tried using 'core.js', 'babel-polyfills', 'babel-plugin-transform-class-properties'.
Here is my webpack.config.js file:
// webpack v4
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, '/dist'),
filename: 'index_bundle.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.styl$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'postcss-loader', 'stylus-loader'],
}),
},
{
test: /\.(png|jp(e*)g|svg|woff|woff2|eot|ttf|otf)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]',
},
}],
},
],
},
devServer: {
port: 8881,
host: '0.0.0.0',
historyApiFallback: true,
},
watch: true,
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
new ExtractTextPlugin(
{ filename: 'app.bundle.css' },
),
],
};
I tried solutions from the questions below which did not help me:
react with IE11 is not working, displaying blank screen
IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
Any help would be appreciated. Thanks in advance.
My mistake. I was using the package 'flexbox-polyfills' which is not supported in the IE.
So, I removed this package and added the 'babel-polyfill' package and its configuration in the webpack.config.js file.
It solved my problem.

React app looking for bundle.js in component folder not project root

The errors I get below are shown in the console after I refresh on a nested route (register/email-confirmation). Whereas non-nested routes do not get this error.
I think the main problem is that it's searching for bundle.js and the image in the nested route path, as opposed to the root path.
The errors in my console:
GET http://localhost:3002/register/bundle.js net::ERR_ABORTED
Refused to execute script from 'http://localhost:3002/register/bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
GET http://localhost:3002/register/a5e694be93a1c3d22b85658bdc30008b.png 404 (Not Found)
My webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BUILD_PATH = path.resolve( __dirname, "./client/build" );
const SOURCE_PATH = path.resolve( __dirname, "./client/src" );
const PUBLIC_PATH = "/";
...
module.exports = {
devtool: 'eval-source-map',
context: SOURCE_PATH,
entry: ['babel-polyfill', SOURCE_PATH + '/index.jsx'],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/, /server/],
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'es2015', 'react', 'stage-1', 'stage-0', 'stage-2'],
plugins: [
'transform-decorators-legacy',
'transform-es2015-destructuring',
'transform-es2015-parameters',
'transform-object-rest-spread'
]
}
}
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
],
},
output: {
path: BUILD_PATH,
filename: "bundle.js",
},
devServer: {
compress: true,
port: 3002,
historyApiFallback: true,
contentBase: BUILD_PATH,
publicPath: PUBLIC_PATH,
},
plugins: [
new webpack.DefinePlugin(appConstants),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'client/src/index.html'),
inject: true
}),
],
watch: true,
}
I don't know about this bug, but I highly recommend using fuse-box
fuse-box is the future of the build systems, within few minutes you will be running your project with high speed hot reload and many others utitilites...
check this react example seed, it's incredibly amazing..

Webpack -p doesn't create bundle correctly

I started learning React by myself and I decided to create a boilerplate for me. I'm getting a problem to build a project using webpack. When I run in dev mode, works fine. When I run the command 'postinstall' to build for production, it generates a bundle.js with only a few bytes. But when I run the 'postinstall' without the parameter -p, it generates my bundle with ~ 2MB, the same thing when generates for dev mode (obviously because is not set for production). I didn't figure out why the production flag isn't creating my bundle correct. Can someone help me with this problem?
The project is in the repository:
https://github.com/ribeiroguilherme/react-boilerplate-dashboard
The webpack.production.config.js file:
const webpack = require('webpack');
const path = require('path');
const ExtractPlugin = require('extract-text-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const plugins = [
new CleanPlugin('dist'),
new ExtractPlugin('bundle.css'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({ minimize: true }),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
];
module.exports = {
devtool: 'eval',
debug: false,
context: __dirname + '/src/client',
entry: {
javascript: './index.jsx',
html: './index.html',
},
output: {
filename: 'bundle.js',
path: __dirname + '/dist',
},
resolve: {
extensions: ['', '.js', '.jsx', '.json'],
root: path.resolve(__dirname, './src/client'),
},
eslint: {
configFile: './.eslintrc',
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'eslint-loader',
},
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel-loader'],
},
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.css$/,
loader: ExtractPlugin.extract('style-loader', 'css-loader'),
},
],
},
plugins: plugins,
};
I'm also worried because the bundle looks pretty big for a project that I just started now. Any hints will be very appreciated.
Best Regards

React-fetch requires react-addons, but there is no react/addons folder

Edit: The author has patched it.
I'm beginning to use react-fetch (well, trying to), and when trying to run webpack, I got this error :
ERROR in ./~/react-fetch/build/react-fetch.js
Module not found: Error: Cannot resolve 'file' or 'directory' E:\Users\Adrien\Documents\GitHub\brigad-admin-frontend/node_modules/react/addons in E:\Users\Adrien\Documents\GitHub\brigad-admin-frontend\node_modules\react-fetch\build
# ./~/react-fetch/build/react-fetch.js 17:19-42
But, as the error says, I have no react/addons folder (I'm using React 15.0.1).
Does anybody have had this issue before?
Thanks in advance.
PS: Here's my webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const nodeDir = `${__dirname}/node_modules`;
const config = {
resolve: {
alias: {
react: `${nodeDir}/react`,
'react-dom': `${nodeDir}/react-dom`,
'react-router': `${nodeDir}/react-router`,
'react-fetch': `${nodeDir}/react-fetch`,
'react-bootstrap': `${nodeDir}/react-bootstrap`,
velocity: `${nodeDir}/velocity-animate`,
moment: `${nodeDir}/moment`,
slimscroll: `${nodeDir}/slimscroll`,
},
},
entry: {
routes: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./public/src/routes/js/main',
],
vendors: [
'react', 'react-dom', 'react-router', 'react-fetch', 'react-bootstrap',
'velocity', 'moment', 'slimscroll',
],
// chartVendors: ['raphael', 'morris'],
},
output: {
path: path.join(__dirname, 'public/dist'),
// publicPath: path.join(__dirname, 'public/dist/'),
filename: 'bundles/[name].bundle.js',
chunkFilename: 'chunks/[name].chunk.js',
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'public'),
loader: 'react-hot',
},
{
test: /\.js$/,
include: path.resolve(__dirname, 'public'),
loader: 'babel',
},
{
test: /\.css$/,
include: path.join(__dirname, 'public'),
loader: 'style!css-loader?modules&importLoaders=1' +
'&localIdentName=[name]__[local]___[hash:base64:5]',
},
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.CommonsChunkPlugin('vendors', './bundles/vendors.js', Infinity),
],
};
module.exports = config;
React API has changed. import React from 'react/addons' isn't valid in the current version. I can see the author uses React.addons.cloneWithProps from there.
The documentation suggests using React.cloneElement instead.
You could tweak the code accordingly and submit a PR to get this fixed.

Resources