How to convert create-react-app script into a static bundle - reactjs

Apologies if this is a strange/stupid question but I have been trying to transition from PHP to more JavaScript orientated development.
I have built a small single-page app with no routing using create-react-app, it is working exactly how I want but I now want to deploy it inside my existing PHP app.
The app does make some API calls so it cannot simply be converted to a static page.
Is there any way I can take what I currently have and convert it into a .js file that can simply be loaded without needing a server?
Thanks

You can do it with webpack devServer
Here an example:
package.json
{
"name": "sampleApp",
"version": "1.0.0",
"description": "",
"devDependencies": {
"webpack": "4.15.0",
"webpack-cli": "3.0.8",
"webpack-dev-server": "3.1.4"
},
"scripts": {
"dev": "webpack --mode development && webpack-dev-server --mode development",
"build": "webpack --mode production && webpack-dev-server --mode production"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sample/sample.git"
}
}
webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
},
devServer: {
contentBase: path.resolve(__dirname, './'),
publicPath: '/build/',
host: '127.0.0.1',
port: 9998,
open: true
},
resolve: {
extensions: ['.ts', '.js'],
}
};

Just execute npm run build and then uplod ./build frolder to your server.

Related

webpack-dev-server --hot - didn't refresh browser files

I have no idea anymore. After updating node.js and webpack, I cannot set reload devServer.
I try with:
mode: "development",
static:
hot: true
and a few more things from google. What am I doing wrong or where is the error? There are no errors in the console. I want to configure webpack to write in ES6, nothing else.
package.json
{
"name": "calc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --hot",
"build": "webpack -d"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.19.3",
"#babel/preset-env": "^7.19.3",
"babel-loader": "^8.2.5",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
}
}
webpack.config.js
const path = require("path");
const entryPath = ".";
module.exports = {
mode: "development",
entry: `./${entryPath}/js/app.js`,
output: {
filename: "out.js",
path: path.resolve(__dirname, `${entryPath}/build`),
},
r: {
static: path.join(__dirname, `${entryPath}`),
hot: true,
compress: true,
port: 3001,
open: true,
headers: { "Access-Control-Allow-Origin": "*" },
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
},
],
},
};
directory structure
Node.js version: v18.9.0
NPM version: 8.19.1
Thanks for the answer.
Please provide your webpack verison.
For webpack 5 use
devServer: {
watchFiles: ['src/**/*.php', 'public/**/*'],
}
See details here https://webpack.js.org/configuration/dev-server/#devserverwatchfiles

Webpack Dev Server Issue

I am learning React, and trying to config webpack and trying to running my app with the webpack-dev-server, but I am getting an error : " Cannot GET / " localhost:9000 and two DevTools Warnings :
Unchecked runtime.lastError: The message port closed before a response was received.
Failed to load resource: the server responded with a status of 404 (Not Found).
*Only Development Mode has this issue.
const path = require('path');
module.exports = {
mode: 'development',
entry: './entrada/index.js',
output: {
path: path.resolve(__dirname, 'saida'),
filename: 'final.js',
},
devServer: {
static: {
directory: path.join(__dirname, 'public'),
},
client: {
logging: 'info',
},
compress: true,
port: 9000,
open: true,
hot: true,
},
}
Package.json >>
scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
}
}

Rebuild with visual studio and webpack-cli does not build my jsx file

I was following this two tutorials to create my first react app and node.js:
Doc Microsoft(The worst doc in MS I have ever seen)
Medium.com This one helped me to build a working site.
I am using visual studio 2019 (not an optional.. so please no VS Code) and to run my application I run the command: npx webpack
It generates the dist folder and the "executable" js. Then I run the project via the "debug" butto in visual studio.
But now I would like to build and run my site as explained in the Micorsoft documentation. The secret seems to be ind the package.json file and webpack-config.js file.
In the first file we find:
"scripts": {
"clean": "",
"build": "webpack-cli ./src/app.tsx --config webpack-config.js"
}
In the second the configuration.
The "only" one difference between my projct and the MS Doc is that the doc uses Typescript.
Here my Project:
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
watch: false,
entry: './src/index.js',
mode: 'development',
output: {
filename: './app.js'
,
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};
package.json
{
"name": "my.web.react",
"version": "0.0.0",
"description": "My.Web.React",
"main": "server.js",
"author": {
"name": ""
},
"dependencies": {
"#babel/core": "^7.15.0",
"#babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"express": "^4.17.1",
"html-webpack-plugin": "^5.3.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"webpack": "^5.49.0",
"webpack-cli": "^4.7.2"
},
"scripts": {
"clean": "",
"build": "webpack-cli ./src/index.jsx --config webpack.config.js"
}
}
babel.config.json
{
"presets": [
"#babel/preset-react"
]
}
Now when I click on Rebuild, nothing happens:
What is still missing?
Thank you

Setting up "npm start" with a newly created React+Typescript webpack app?

I need a bit of help with initial setup of webpack to serve my app with hot reloading. I've followed this guide to set up React+Webpack with Typescript, but I'd like to know how I can go about setting it up so I can call "npm start" and have it compile and host the app, with hot reloading.
My webpack.config.js looks like the following:
module.exports = {
mode: "production",
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx"]
},
module: {
rules: [
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
};
And my package.json looks like this:
{
"name": "client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "DMW",
"license": "ISC",
"devDependencies": {
"#types/react": "^16.9.15",
"#types/react-dom": "^16.9.4",
"source-map-loader": "^0.2.4",
"ts-loader": "^6.2.1",
"typescript": "^3.7.3",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"dependencies": {
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"keywords": []
}
I'd really appreciate it if someone could link me to something to get this working. I'm a bit intimidated by the search results I've found.
EDIT: I ended up using npx create-react-app app --template typescript instead, as detailed here: https://create-react-app.dev/docs/adding-typescript/
Welcome to the community.
Regarding the settings for webpack try adding this to your package.json
"scripts": {
"start": "webpack-dev-server --mode development --open --hot"
},
When you do npm start, start will be taken from this script and would run app as webpack. Also --hot will ensure that hot reload is true, i.e. reload on any changes that you do to the app automatically.
Be sure to change the mode to production when pushing the app to production so that you don't get all the errors and warnings in the production. Hope it helps !!

asp.net core 2.1 Webpack 4 React not starting correctly

Can not figure out, why when I am simply running npm run start from command line, project starts up and everything seems to be working fine.. But If I am trying to start it on IIS from Visual studio it starts browser window (which gets timed out "The create-react-app server did not start listening for requests within the timeout period of 50 seconds").
And after few seconds it starts a second browser tab, on new port, which loads my project as desired..
I very believe there is problem with my StartUp.cs, just cant figure out, where and why..
If needed I can provide any additional needed information.
My project structure:
web
|
bin-
ClientApp
|
dist-
node_modules-
public- index.html
src - index.tsx
package.json
tsconfig.json
tslint.json
webpack.config.js
Controllers-
obj
Pages
Properties
appsettings.Development.json
appsettings.json
Program.cs
Startup.cs
Additionaly screen shot, of exact structure
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "[name].bundle.js",
path: __dirname + '/dist',
},
devtool: 'source-map',
resolve: {
extensions: ['.js', '.json', '.ts', '.tsx'],
},
module: {
rules: [{
test: /\.(ts|tsx)$/,
loader: 'awesome-typescript-loader',
},
{
test: /\.html$/,
use: [{
loader: "html-loader",
options: {
minimize: true
}
}]
},
{
test: /\.css$/,
use: [{
loader: 'style-loader',
}, {
loader: 'css-loader',
}, ],
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
package.json
{
"name": "ClientApp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.1.0",
"#babel/preset-env": "^7.1.0",
"#babel/preset-react": "^7.0.0",
"awesome-typescript-loader": "^5.2.1",
"babel-loader": "^8.0.2",
"css-loader": "^1.0.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"install": "^0.12.1",
"mini-css-extract-plugin": "^0.4.2",
"react": "^16.5.1",
"react-dom": "^16.5.1",
"style-loader": "^0.23.0",
"tslint": "^5.11.0",
"typescript": "^3.0.3",
"webpack": "^4.19.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.8"
},
"dependencies": {
"#types/react": "^16.4.14",
"#types/react-dom": "^16.0.7"
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Web
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
}
tsconfig.json
{
"compilerOptions": {
"noImplicitAny": true,
"sourceMap": true,
"target": "es6",
"jsx": "react",
"moduleResolution":"node",
"allowSyntheticDefaultImports": true,
"module": "ESNext",
},
"exclude": [
"node_modules"
],
}
I create a new react template using your configure above and find out that when the command npm run build fails or npm start fails , or when the AspNetCore cannot find the correct URL to the Webpack Dev Server , it will complain the same error as you described :
which gets timed out "The create-react-app server did not start listening for requests within the timeout period of 50 seconds"
Quick fix
As the error describes , it seems that there's something wrong with the react-scripts . However , when I look into the package.json file, I find there's no create-react-app dependencies configured at all .
So I add a react-scripts dependencies by npm i react-scripts --save-dev
"react-scripts": "^1.1.5",
and replace your npm start and build with :
"scripts": {
"start": "rimraf ./build && react-scripts start",
"build": "react-scripts build"
},
Now it works fine when launched in Visual Studio .
Launching without react-scripts
Since you said it worked fine by npm start. I guess the reason is the ASP.NET Core cannot find the correct URL served on Webpack dev server .
So I create another new react project with your package.json :
"scripts": {
"start": "webpack-dev-server --port 3000 --mode development --open",
"build": "webpack --mode production"
},
As the default dev server listens on Port 3000, and the contentBase is /public , so I add a configuration in your webpack.config.js:
devServer: {
contentBase: __dirname + "/public/",
inline: true,
port: 3000,
},
I notice that you have dependencies on babel , so I add a .babelrc config and a dependency on #babel/plugin-proposal-class-properties :
{
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
],
"presets":["#babel/env","#babel/react"]
}
Also , I don't know whether you have files of jsx or not , so I just add a rule on webpack.config.js:
{
test:/\.jsx?/,
loaders:['babel-loader']
},
Because I have already got a index.html (generated by template) , I remove the HtmlWebPackPlugin configuration :
plugins: [
// new HtmlWebPackPlugin({
// // template: "public/index.html",
// // // filename: "index.html"
// }),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
When I test the default react template (havingthe default package.json replaced with yours ) , it works fine now .
The create-react-app server did not start listening for requests within the timeout period of 50 seconds
that happened to me only on startup so I added spa.Options.StartupTimeout:
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.Options.StartupTimeout = TimeSpan.FromSeconds(120);
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
As hinted at by the error message, the React development server middleware for Asp.NET Core is tied to create-react-app. It will not work when invoking the Webpack dev server directly. It scans the output of the script for the text "Starting the development server" which is specific to create-react-app.
You can get around it by setting the start command in package.json as follows:
"start": "echo Starting the development server && node node_modules/webpack-dev-server/bin/webpack-dev-server.js --port %PORT% --mode development"
This makes Asp.Net Core middleware happy and it also makes the dev server listen on the right port.
Alternatively, you can try convert your setup to get rid of the full Webpack setup and use create-react-app.
Please note that there seems to be an issue in the answer provided by itminus. The second section, launching without react-scripts, cannot work because the create-react-app "Starting the development server" will not be there.

Resources