Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a public folder to react-boilerplate webpack config?

I'm setting up a new web app using react and its boilerplate the react-boilerplate. Now I want to add a public folder in the root that contains the index.html as well as the robot.txt .htaccess files and some external js libraries. Can someone please guide me through editing the webpack config files to make it behave like so.

Thanks in advance

like image 731
Nader Zouaoui Avatar asked May 06 '19 14:05

Nader Zouaoui


People also ask

How do I reference a public folder in React?

To reference assets in the public folder, you need to use an environment variable called PUBLIC_URL . Only files inside the public folder will be accessible by %PUBLIC_URL% prefix.

What is public and SRC in react?

There are 3 main approaches to store images in react app: src folder - Images stored in this directory will be included in the final bundle. Additionally, they have the added bonus of being able to be imported as a JavaScript module. public folder - Files in public directory will not be processed by Webpack.

What is the role of the Public folder in React?

The public folder contains static files such as index. html, javascript library files, images, and other assets, etc. which you don't want to be processed by webpack. Files in this folder are copied and pasted as they are directly into the build folder.


1 Answers

You could use copy-webpack-plugin to copy files from public folder to your build folder. Make the next steps to make it works:

  1. Install copy-webpack-plugin:
npm i copy-webpack-plugin --save-dev
  1. Edit your webpack.base.babel.js in /internals/webpack:
const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin'); <-- import plugin

module.exports = options => ({
    ...
    plugins: options.plugins.concat([
        ...
        new CopyWebpackPlugin([ <-- add plugin 
            {
                from: 'public',
            },
        ]),
  ]),

  1. Now you can create folder public in your source root and all files from this folder will be copied to build folder.

IMPORTANT! You already have index.html which is generated from /app/index.html template by HtmlWebpackPlugin. If you created index.html in your public folder, it could override generated one.

like image 105
Andrii Golubenko Avatar answered Nov 07 '22 20:11

Andrii Golubenko