where does /static/js folder come from? - reactjs

I'm new to React, just a question on the bundle js files produced by webpack.
Currently when I I run my app, and I check chrome dev tool, I found 0.chunk.js, bundle.js, main.chunk.js are under localhost/static/js, I don't have static folder in my react app, so where does /static/js folder come from? was it create by chrome?

Those files are generated by webpack.
To specify, you can run command npm run eject then you can see a folder named scripts.
In this folder, first let's check file start.js where run when you run npm start.
const devServer = new WebpackDevServer(compiler, serverConfig);
It using WebpackDevServer create a dev server run on your local to host your app, so you can access app through localhost:3000. Next let's check compiler parameter.
const compiler = createCompiler({
appName,
config,
devSocket,
urls,
useYarn,
useTypeScript,
webpack,
});
Inspect config you can see it created from configFactory
const config = configFactory('development');
Check configFactory you can see it is a function return server configuration as an object include property named output.
output: {
...
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// TODO: remove this when upgrading to webpack 5
futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
}
Here is what you are looking for.

Related

I want to "Gatsby Build" and deploy to a subdirectory

I read https://www.gatsbyjs.org/docs/path-prefix/ and I added the following to gatsby-configs.js.
{
pathPrefix: "/modules/custom/gatsby/gatsby-shopify-starter/public",
},
And, I execute sudo gatsby build --prefix-paths on terminal.
But, I got this error message.
ERROR
The "path" argument must be of type string. Received an instance of Object
Error: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type s tring. Received an instance of Object
What am I doing wrong?
Gatsby's pathPrefix only prepends a string to your projects routes (url). Your deployment script(s) should handle where the public folder ends up on your server. If you really want to publish your gatsby project to somewhere other than /public (locally) You will propbably need to do something like use fs and path in onPostBuild in gatsby-node.js to move everything over to another directory. At the time or writing this, Gatsby doesn't directly support alternative build directories so you are on your own when using gatsby develop or gatsby serve to view this locally.
Try something like this in gatsby-node.js but change the paths to serve your needs. This example will publish your project to /public/blog rather than the default /public and is just a proof of concept but I tested it and it works:
const path = require('path');
const fs = require('fs');
exports.onPostBuild = function() {
fs.renameSync(path.join(__dirname, 'public'), path.join(__dirname, 'public-blog'));
fs.mkdirSync(path.join(__dirname, 'public'));
fs.renameSync(path.join(__dirname, 'public-blog'), path.join(__dirname, 'public', 'blog'));
};

Run React dev server inside another application

In our old .jsp application, we are integrating react.
My react dev server is running on http://localhost:3000 and existing application at http://localhost:8100.
I included all the required js & CSS files of reacting into JSP page. which is working fine.
When when I'm using lazy-loading in React, for ex:
import('some-file.js').then(file => {
// Some work
});
In this case Webpack is trying to load chunk from localhost:8100 instead of Dev server.
I'm using react-script for development and build.
Try to add publicPath like below in webconfig.js files.
output: {
//
publicPath: 'http://localhost:3000/static/js/dist' or
// publicPath : 'http://localhost:3000/dist'
}

Heroku "content not from webpack is served from /app/public" despite using all default create-react-app config

I'm deploying a pretty basic front-end only React app (essentially a static site) to Heroku via an auto-deploy integration with Github. I've done this before with a more complicated app and had no issues. But now I'm getting the following output in my logs when I deploy:
2020-05-02T11:18:53.190530+00:00 app[web.1]: [34mℹ[39m
[90m「wds」[39m: webpack output is served from
2020-05-02T11:18:53.190635+00:00 app[web.1]: [34mℹ[39m
[90m「wds」[39m: Content not from webpack is served from /app/public
2020-05-02T11:18:53.190727+00:00 app[web.1]: [34mℹ[39m
[90m「wds」[39m: 404s will fallback to /
2020-05-02T11:18:53.190910+00:00 app[web.1]: Starting the development
server...
2020-05-02T11:18:53.190912+00:00 app[web.1]:
2020-05-02T11:18:53.287654+00:00 heroku[web.1]: State changed from
starting to crashed
When I first got this, the statement was accurate. I had a few images that I was loading like src='/image.jpg'. But I moved all assets that I'm actually using in my app into src/images and am importing them as components now. I've gone over every file in my src directory four times and there are no longer any references to files in the public directory.
I haven't done any custom Webpack configuration, it's all default CRA. So why does it still throw this error and how do I resolve it?
Project hierarchy:
├── src
│ └── index.js
│ └── app.js (etc)
│ └── images (this is where I am importing any images into my components now)
├── public
│ ├── index.html
│ ├── favicon.jpg
│ │── manifest.json
│ └── robots.txt
├── package.json
├── package-lock.json
├── .gitignore
webpack.config.js
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
].filter(Boolean),
output: {
// The build folder.
path: isEnvProduction ? paths.appBuild : undefined,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// TODO: remove this when upgrading to webpack 5
futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
// webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// We inferred the "public path" (such as / or /my-project) from homepage.
publicPath: paths.publicUrlOrPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
// Prevents conflicts when multiple webpack runtimes (from different apps)
// are used on the same page.
jsonpFunction: `webpackJsonp${appPackageJson.name}`,
// this defaults to 'window', but by setting it to 'this' then
// module chunks which are built will work in web workers as well.
globalObject: 'this',
},
So, I got a Solution, Heroku uses nodejs buildpack as default. You'll need to add that of CRA(Create react App).
First, check the build pack you're using heroku buildpacks -a <appname>
then change to CRA buildpack heroku buildpacks:set mars/create-react-app -a <appname>
Then redeploy.
You can read this article for more configuration
Heroku uses default build pack as heroku/nodejs.Need too changes your buildpack configuration in your heroku app settings.
You can use add below git url as build pack for react app
https://github.com/mars/create-react-app-buildpack
You can add object "engines" inside package.json (version node & npm using build your app)
"engines": {
"node": "10.15.3",
"npm": "6.14.5"
}
***check version : node -v & npm -v
P/s: It's working with me.

Webpack Dev Server Issues

I am building a web application using Express + React.
I am dealing with a issue with WEbpack Dev Server.
My Webpack Dev Server builds the bundles just fine!
But, I have an issue with the way the files are served.
Usually , we name the root html file as index.html, but because of my Web application architecture , I cannot use index.html and have instead name it client.html.
This brings me to the problem that I am facing, the webpack dev server looks for the index.html when I go to localhost:8080, as I am using client.html the webpack dev serves asks me to select my file.
Webpack Static file select screen
So , is there a way to load client.html directly when I access localhost:8080(Webpack Dev Server).
Thanks in Advance!
In your webpack.config.js file you can add the configurations for the webpack dev server
devServer: {
historyApiFallback: {
rewrites : [
{from: /^\/$/, to: './client.html'}
]
}
}
This will redirect your default index.html to the client.html
For more details see the DevServer documentation

How to parameterize variables in a React Webpack app for different environments?

I'm working on a React web app which was created by create-react-app and I am getting ready to deploy it.
The issue is, for development, the app uses the api instance running on my dev environment (localhost:{api-port}) but for the deployed app this should point to the server api instance (api.myapp.com).
Currently the host is just a variable in my networking component:
const hostname = 'localhost:9876'
I plan on using webpack to generate the static files which will be served by the production front-end, and I would like to continue developing using npm start as set up by create-react-app.
What would be the correct way to set up my project such that the host can be set automatically to the correct value based on whether I'm running the dev server or building for production?
A common solution is to check against process.env.NODE_ENV like this:
const hostname = process.env.NODE_ENV === "development" ? "localhost:9876" : "localhost:6789";
You may need to force the environment variable to be present in your Webpack configuration file using the DefinePlugin like this:
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV:JSON.stringify(process.env.NODE_ENV || "development")
}
})
]
An alternative solution might be to use the config package and provide your hostname string as a configuration parameter. config will inherit configurations from files based on the current NODE_ENV. It will start by using configuration from a default.json file, then override it with a development.json, or production.json, depending on your environment.
Note that you'll need for the config files to be copied to your output directory using CopyWebpackPlugin for it to work.
There are definitely many ways you could achieve that. One of those solutions would be to use webpacks's DefinePlugin. In your plugins section in webpack configuration you would add something like this:
new webpack.DefinePlugin({
API_HOST: process.env.NODE_ENV === 'production'
? JSON.stringify('localhost:8080')
: JSON.stringify('api.com')
}),
That creates a global variable API_HOST available everywhere in your codebase, which you can use. You can read more about the DefinePlugin here https://webpack.js.org/plugins/define-plugin/
you could use a relative path when you make any request to your api server instead of calling the full url for your app.
and for your development you could add a proxy property to your package.json file:
{
...
"proxy": {
"/api/*": {
"target" :"http://localhost:9876"
}
}
}
so whenever you make any request that prefixed with /api will be redirected to http://localhost:9876/api this is just in the development but in the production if you make a request prefixed with /api it won't be redirected it will be served normally because the proxy is just available in the dev server coming with create-react-app.

Resources