How to deploy ReactJS app into subdirectory with webpack

Thu Pham Anh
2 min readFeb 23, 2020

Deployment is one of important steps when you build an app by ReactJS. So do you know how to deploy ReactJS app into subdirectory? Most of cases you deploy into root directory on server, like htdocs folder. But sometimes, you want to deploy app into subdirectory. And you don’t know how to do this? Don’t worry, it’s very simple.

Deploy ReactJS app into subdirectory

How to setup webpack in your ReactJS project?

Firstly, we are going to setup webpack for ReactJS project. Open terminal in your project folder and run following commands:

npm i webpacknpm i html-loader html-webpack-plugin mini-css-extract-plugin url-loader clean-webpack-plugin path --save-dev

First command will install webpack into your project. And second one will install all dependencies that help you handle output files when build.

Now, we have to create new file at root folder of project called webpack.config.json. Then copy code below and paste into it:

You can see how to webpack handle all type of files in your project in this file. For more infomation, you can find it in webpack documentation here https://webpack.js.org/

So you have just finished config webpack to deploy your project to root directory in server. Next step is config it to deploy into subdirectory.

Deploy ReactJS app into subdirectory with webpack

Firtsly, you need to determine what is your subdirectory name. For example, assume that you want to deploy your app into htdocs/admin folder in server. So subdirectory name in this case is admin.

Set ouput path

Very simple, you have to do is change publicPath variable in webpack.config.js like this:

const publicPath = '/your-subdirectory-name/';

Set a Basename

While developing an application using the react platform, we need to set a basename attribute on the react-router (or react-router-dom) to tell the router that the application will be served from the subdirectory.

<Router basename={'/your-subdirectory-name'}>
<Route path='/' component={Home} />
{/* … */}
</Router>

Finally, open terminal in root of your project and run following command:

npm run build

The output files and assets will be generated in build folder (or dist folder or something like this). Now you can transfer all files in this folder into subdirectory in server.

Well, app is deployed. But wait… When reload app at any url, server return 404 error. Oh no!!!

Don’t worry. The rest thing is create .htaccess to solve this problem.

Create new file in your subdirectory in server, and paste code below:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /your-subdirectory-name/
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /your-subdirectory-name/index.html [L]
</IfModule>

All done! Now your app is deployed and works perfectly!

Happy coding!

--

--