Search code examples
sitemaprobots.txtxml-sitemapwebpack

How to copy sitemap.xml to build folder with React & Webpack?


I have a sitemap.xml file in public folder. When I build the React application, the sitemap.xml file is not present in the dist/build folder.

What Webpack configuration is needed to achieve that? How does robots.txt need to be set up?


Solution

  • Here is the webpack-config for serving a file to build folder witha a custom name

    enter image description here

    module: {
        rules: [
            {
                test: /\.(ts|js)x?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                    },
                ],
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(?:ico|gif|png|jpg|jpeg|xml)$/i,
                type: 'asset/resource',
            },
            {
                test: /\.xml/,
                type: 'asset/resource',
                generator: {
                    filename: 'sitemap.xml',
                },
            },
            {
                test: /\.txt/,
                type: 'asset/resource',
                generator: {
                    filename: 'robots.txt',
                },
            },
            {
                test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
                type: 'asset/inline',
            },
        ],
    },
    

    Finally make sure you import that file inside your react application or else it will not be served to build folder

    enter image description here