React Routes not working after building the app using webpack - .htaccess

React Routes not working after building the app using webpack
The routes are working fine when I am running the app using the webpack server (npm start)
webpack.config file
var webpack = require('webpack');
module.exports = {
entry: {
'index': [
'webpack-dev-server/client?http://localhost:8080/',
'webpack/hot/only-dev-server',
'./index.jsx'
]
},
output: {
path: __dirname,
filename: "[name].js",
publicPath: 'http://localhost:8881/',
chunkFilename: '[id].chunk.js',
sourceMapFilename: '[name].map'
},
resolve: {
extensions: ['', '.js', '.jsx', '.es6'],
modulesDirectories: ['node_modules']
},
module: {
loaders: [
{test: /\.jsx$|\.es6$|\.js$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/},
{test: /\.scss$|\.css$/, loader: 'style-loader!style!css!sass'}
]
},
plugins: [
new webpack.NoErrorsPlugin()
],
devtool: "eval-source-map",
devServer: {
port: 8080,
historyApiFallback: {
index: '/'
}
},
externals: {
'Config': JSON.stringify({
serverUrl: "http://pss/",
authSuccessUrl: "http://localhost:8881/loginSuccess",
podioClientId: "property-seller-solutions"
})
}
};
package.json file:
{
"name": "pss",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --hot --port 8080"
},
"author": "",
"license": "BSD-2-Clause",
"devDependencies": {
"babel": "~6.5.2",
"babel-core": "~6.9.1",
"babel-loader": "~6.2.4",
"babel-preset-es2015": "~6.9.0",
"babel-preset-react": "~6.5.0",
"babel-preset-stage-0": "~6.5.0",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.0",
"gulp-html-replace": "^1.6.1",
"gulp-react": "^3.1.0",
"gulp-uglify": "^1.5.4",
"history": "~3.0.0",
"react": "~15.1.0",
"react-dom": "~15.1.0",
"react-hot-loader": "~1.3.0",
"webpack": "~1.13.1",
"webpack-dev-server": "~1.14.1"
},
"dependencies": {
"chart.js": "^2.1.6",
"connect-history-api-fallback": "~1.2.0",
"halogen": "^0.2.0",
"highcharts": "^4.2.5",
"react-d3-basic": "^1.6.11",
"react-infinite-scroll-component": "^1.4.1",
"react-infinite-scroll-es2015": "^1.0.0"
}
}
.htaccess File:
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
After building the app (webpack --hot --inline), got two output files - index.js and index.html
I copied the two files and the .htaccess file to my localhost root folder.
The index route is working fine..(http://localhost), but when I am trying to redirect to http://localhost/home its showing "404 Not Found" Error (The requested URL /home was not found on this server.)
These routes are working fine when I am running the app using the webpack server (npm start) - http://localhost:8080/home

Worked.
Used the following .htaccess code:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /index.html [L]
And used the following terminal command to build the project using webpack:
webpack --inline --history-api-fallback --progress -p

You need to configure your app to serve index.html when visiting /home.

To my understanding,if you say http://localhost:8080/home it will made server-side router call. You need it setup it first,
https://github.com/reactjs/react-router/blob/master/docs/guides/ServerRendering.md

Related

How to build (Webpack) the Node Js project using PUG Engine?

I am stuck to build the node js project using webpack and I am using pug engine for front end.
My Project Structure:
bin
controller
- csv.controller.js
public
- stylesheets
- javascript
- images
routes
- csv.route.js
- index.route.js
views
- layouts
-- layout.pug
-index.pug
app.js
Package.json File
{
"name": "csv",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "webpack --mode=production",
"build:dev": "webpack --mode=development",
"start":"nodemon ./app.js",
"start:dev": "webpack-dev-server --mode=development"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "^1.7.4",
"cookie-parser": "~1.4.4",
"csv-parser": "^2.3.1",
"csv-writer": "^1.5.0",
"debug": "~2.6.9",
"express": "^4.17.1",
"express-fileupload": "^1.1.6-alpha.5",
"fast-csv": "^3.4.0",
"http-errors": "~1.6.3",
"morgan": "^1.9.1",
"multer": "^1.4.2",
"npm-check-updates": "^3.1.23",
"request": "^2.88.0"
},
"devDependencies": {
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.2.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"pug": "^2.0.4",
"pug-loader": "^2.4.0",
"style-loader": "^1.0.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.1",
"webpack-merge": "^4.2.2"
}
}
Actually what I want, after build, A dist folder contain a build.js or whatever its name and all public folder assets in the same directory. I tried with some below codes to build the project.
Webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
entry: {
app: "./app.js"
},
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js"
},
devServer: {
port: 3000
},
plugins: [
new HtmlWebpackPlugin({
template: "./views/index.pug"
})
],
module: {
rules: [
{
test: /\.pug$/,
use: ["pug-loader"]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: [/.js$/],
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
}
if (argv.mode === "production") {
}
return config;
};
I know this question is old, but just in case somebody is looking for an answer.
You need another Webpack config for app.js, which is express entry point.
Call it webpack.server.js or webpack.server.config.js or whatever convenient. Make sure to include webpack-node-externals:
https://www.npmjs.com/package/webpack-node-externals
It may look something like this:
//webpack.server.js
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
return ({
entry: {
app: ./src/server/app.js,
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js',
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
});
};
Also use webpack-dev-middleware in your app.js.
See the below link:
https://webpack.js.org/guides/development/
In package.json include a script that looks something like this:
"server:dev": "webpack --config webpack.config.js && webpack --mode development --config webpack.server.js && node ./dist/app.js",
In your webpack.config.js make the entry point the js file that imports your front-end assets..
That is your stylesheets and any other js codes..
Not sure what css framework you are using.
But, I am using tailwindcss and I have a js entry point file that imports tailwindcss and my other js codes.
So essentially you may need two webpack config files one for the front-end and one for the express server.
Hope I am making sense.

npx webpack Unexpected token :

I am trying to use Webpack for the first time with Node and Babel (this is my first time using Babel as well) on Windows 10. I think I have everything configured properly, but it's giving me a cryptic error:
The same thing happens if I do npx webpack --exec bable-node.
In everything I've read about this, it gives a line number. I'm not sure what's the issue.
I have all of the files I thought were related to Node in a folder called "node", and all the other files in a folder called "src". I don't know if this is causing the issue. Here is the folder structure:
/node
/config
/node_modules
.babelrc
master-updated.sh
package-lock.json
package.json
server2.js
webpack.config.js
/src
/model (this is has a bunch of js files, but I removed the references to them for now)
/public
/html
/srcipts
/stylesheets
/css
/scss
/vue
.gitignore
master-updated.sh is a shell script for responding to a GitHub webhook.
Here is the beginning of server2.js:
'use strict';
process.env.NODE_CONFIG_DIR = './node/config';
const config = require('config'),
babel = require('babel-core'),
ejs = require('ejs'),
util = require('util'),
express = require('express'),
bodyParser = require('body-parser'),
cors = require('cors'),
moment = require('moment'),
plaid = require('plaid'),
mariadb = require('mariadb'),
fs = require('fs'),
http = require('http'),
https = require('https'),
session = require('express-session'),
exec = require('child_process').exec;
const GOOGLE_AUTH_CLIENT_ID = '<REDACTED>';
const { OAuth2Client } = require('google-auth-library');
const googleAuthClient = new OAuth2Client(GOOGLE_AUTH_CLIENT_ID);
const APP_PORT = config.APP_PORT;
Here is my webpack.config.js file:
module.exports = {
target: 'node',
entry: {
app: ['./server2.js']
},
output: {
filename: 'server.js',
path: path.resolve(__dirname, 'test')
},
module: {
loaders: [
test: '/\.js$/',
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ["#babel/preset-env"]
}
]
}
}
Here is .babelrc:
{"presets": ["#babel/preset-env"]}
And here is package.json:
{
"name": "sage-savings",
"version": "0.0.1",
"description": "An app for easy budgeting.",
"main": "server2.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config node/webpack.config.js",
"start": "node node/server2.js"
},
"author": "Dakota Dalton",
"repository": "https://github.com/1silvertiger/Sage",
"license": "ISC",
"dependencies": {
"#types/express": "^4.16.1",
"aws-sdk": "^2.397.0",
"body-parser": "^1.18.3",
"config": "^3.0.1",
"cors": "^2.8.5",
"ejs": "^2.5.9",
"express": "4.16.x",
"express-session": "^1.15.6",
"google-auth-library": "^3.0.1",
"mariadb": "^2.0.3",
"moment": "^2.22.2",
"mysql": "^2.16.0",
"plaid": "2.x.x"
},
"devDependencies": {
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"ajv": "^6.10.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.5",
"babel-preset-env": "^1.7.0",
"typescript": "^3.3.3333",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3"
}
}
These syntax problems are easily identified if you use an IDE which has syntax highlighting, for example VS Code. All I did was copy your config into a file and load it into VS Code.
You are incorrectly closing the regular expression used for exclude:
exclude: /node_modules\,
You must use a forward slash instead of a back slash:
exclude: /node_modules/
You also need to wrap your loader in an object literal:
loaders: [
{ // <= wrap in object literal
test: '/\.js$/',
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ["#babel/preset-env"]
}
}
]

NODE.JS: Why can't I get live reload with web pack?

IM SO FRUSTRATED RIGHT NOW, ive spent a whole day trying to get webpack to work, but every tutorial or documentation is terrible..it shouldnt be this hard..whats the point of these packages if they actually make you spend more time trying to configure them then saving time.
I just want the live reload to work. I've tried the inline method, iframe, hot module, the middleware with express. None of it works...Im using Node.js on atom, with safari browser.
I want it to work with express.
Can someone point me to a good tutorial...or explain step by step very simply..
Need help. please. no one every replies on these things! Thank you
GITHUB REPO LINK
webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports =
{
entry: './app.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname + '/dist',
filename: 'app.bundle.js',
},
devServer: {
port: 8000,
open: true,
inline: true
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
package.json
{
"name": "clinic8beauty",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"b": "webpack",
"s": "webpack-dev-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"babel": {
"presets": [
"es2015"
]
},
"author": "Kosta Pontidas",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"events": "^1.1.1",
"express": "^4.15.2",
"jquery": "^3.2.1",
"pug": "^2.0.0-beta.12",
"twilio": "^2.11.1",
"validator": "^7.0.0"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"node-sass": "^4.5.2",
"pug-html-loader": "^1.1.4",
"sass-loader": "^6.0.3",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4",
"webpack-hot-middleware": "^2.18.0",
"webpack-node-externals": "^1.5.4"
}
}
app.js requires
const express = require('express'),
app = express(),
events = require('events'),
eventEmitter = new events.EventEmitter(),
bodyParser = require('body-parser'),
validator = require('validator'),
client = require('twilio')('AC3cdbdc7ecb720d5521f41243450343e8',
'8f76c52d839dc25aa17ddc72b3b9d781');
You have target node in your config change it to web or remove it as default is web. It should fix your problem.
Can you try the following?
const nodeExternals = require('webpack-node-externals');
const path = require('webpack'); // <== added
module.exports =
{
entry: './app.js',
// target: 'node', <== deleted
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'), //<== added
filename: 'app.bundle.js'
},
devServer: {
port: 8000,
open: true,
inline: true,
contentBase: [path.resolve(__dirname, 'dist')/* add other directories if needed */]
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
And run webpack-dev-server --progress instead of just webpack to start the server
Why not use nodemon globally and webpack to compile

How do I deploy my reactJS application on web server public to internet

I started following reatJS tutorial from Youtube, now I want to share my learning step by step with the LEAD developers over internet.
I have npm /node js installed on my macbook, and I after I finish work i run npm start and it gives me local host address on port 8081 , but I have apache web server running on different machine which is open to internet , so I want to deploy my reactJS app using npm / webpack to this computer running apache.
I have this package.json file setup.
{
"name": "react-basics",
"version": "1.0.0",
"description": "Some Basics ReactJS",
"main": "index.js",
"scripts": {
"start": "npm run build",
"build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot",
"build:prod": "webpack -p && cp src/index.html dist/index.html"
},
"keywords": [
"reactJS"
],
"author": "Ciasto Piekarz",
"license": "MIT",
"dependencies": {
"react": "^15.5.3",
"react-dom": "^15.5.3"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^6.4.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"webpack": "^2.3.3",
"webpack-dev-server": "^2.4.2"
}
}
and webpack.config.js
var webpack = require("webpack");
var path = require("path");
var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");
var config = {
entry: SRC_DIR + "/app/index.js",
output: {
path: DIST_DIR + "/app",
filename: "bundle.js",
publicPath: "/app/"
},
module: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["react", "es2015", "stage-2"]
}
}
]
}
};
module.exports = config;
Do I have to install npm /node.js on remote machine as well which is open to internet ? can I not just use apache web server ? if so how do I just stick to port 80 ?
I think you just need to run npm run build:prod. It will probably generate a dist folder, which should be uploaded on your server and used as your webroot folder for apache.

Electron and Webpack ENOENT: no such file or directory, open '/path.txt'

I am a beginner trying to use Electron (formerly Atom) and Reactjs bundled with Webpack. Everything was working fine until I tried to use Electron's remote module to access the mainWindow in my React components.
Trying to import this module, I get the infamous error:
Uncaught Error: ENOENT: no such file or directory, open '/path.txt'
I've tried reinstalling electron and I've checked node_modules/electron, and found that path.txt is there.
Here is my webpack.config.js:
var webpack = require('webpack');
module.exports = {
context: __dirname,
entry: {
app: ['webpack/hot/dev-server', './src/App.jsx'],
},
target: 'node',
output: {
path: './public/built',
filename: 'bundle.js',
publicPath: 'http://localhost:8080/built/'
},
devServer: {
contentBase: './public',
publicPath: 'http://localhost:8080/built/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: /src/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.(png|jpg)$/,
loader: 'file-loader?name=[path][name].[hash].[ext]'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
And here is my package.json:
{
"name": "app",
"version": "0.1.0",
"main": "main.js",
"description": "description",
"license": "UNLICENSED",
"repository": {
"type": "git",
"url": "https://github.com"
},
"scripts": {
"start": "./node_modules/.bin/electron .",
"watch": "./node_modules/.bin/webpack-dev-server"
},
"dependencies": {
"electron": "^1.3.5",
"radium": "^0.17.1",
"react": "^15.0.1",
"react-dom": "^15.0.1"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.7.7",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.24.0",
"file-loader": "^0.9.0",
"style-loader": "^0.13.1",
"webpack": "^1.13.0",
"webpack-dev-server": "^1.14.1"
}
}
I suspect that it may have something to do with the start script in package.json as the path.txt is not in the same directory as node_modules/.bin/electron. However, I haven't figured out how to solve this.
in case it's not to late, you simply need to replace your "node" target with "electron-renderer" in your webpack.config.js
Just run command like below
cd node_modules/electron && node install.js
It will create path.txt file
For Mac the file contains like below
dist/Electron.app/Contents/MacOS/Electron

Resources