简体   繁体   中英

Set publicpath in ReactJs project with Webpack 4

I'm using webpack 4 with ReactJs project. My project directory:

project-react-app
├── dist
├── src
|   └── components
|   └── public
|       └── css
|       └── js
|       └── img
├────── store
├────── index.html
├────── index.js
└────── app.js

So, I'm trying to use my css, js and images in public folder to use in my index.html file. But I can't load the images from the public folder. So, I try to set output publicPath for this folder in webpack config.

entry: './src/index.js',
output: {
   path: '/dist',
   publicPath: '/public/',
   filename: 'javascripts/[name].js',
   libraryTarget: 'umd',
},

The result is Cannot GET / All my webpack.config.js

const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const dotenv = require('dotenv');
const webpack = require('webpack');
const path = require('path');

module.exports = () => {
  const env = dotenv.config().parsed;

  const envKeys = Object.keys(env).reduce((prev, next) => {
    prev[`process.env.${next}`] = JSON.stringify(env[next]);
    return prev;
  }, {});

  return {
    module: {
      rules: [
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: ['babel-loader', 'eslint-loader'],
        },
        {
          test: /\.html$/,
          use: [{
            loader: 'html-loader',
            options: {
              minimize: true,
            },
          }],
        },
        {
          test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader'],
        },
        {
          test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
          loaders: ['file-loader'],
        },
      ],
    },
    entry: './src/index.js',
    output: {
      path: '/dist',
      publicPath: '/public/',
      filename: 'javascripts/[name].js',
      libraryTarget: 'umd',
    },
    plugins: [
      new HtmlWebPackPlugin({
        template: path.resolve(__dirname, 'src/', 'index.html'),
        filename: 'index.html',
      }),
      new MiniCssExtractPlugin({
        filename: '[name].css',
        chunkFilename: '[id].css',
      }),
      new webpack.DefinePlugin(envKeys),
    ],
    node: {
      fs: 'empty',
    },
    devServer: {
      historyApiFallback: true,
    },
    devtool: 'source-map',
    optimization: {
      splitChunks: {
        chunks: 'async',
        minSize: 30000,
        maxSize: 0,
        minChunks: 1,
        maxAsyncRequests: 5,
        maxInitialRequests: 3,
        automaticNameDelimiter: '~',
        automaticNameMaxLength: 30,
        name: true,
        cacheGroups: {
          vendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
          },
          default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true,
          },
        },
      },
    },
  };
};

What is the configuration for my purpose? And run the React project properly? Thanks

What you are trying to do is very hacky, unsafe and just not the way it should be done. Any content you want to serve to the user should be in the dist folder.

The fact that it isn't means that you are using webpack wrong.

You should import the image and use it like this:

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;

along with a image loader -- for example:

{
    test: /\.(svg|png|jpg|jpeg|gif)$/,
    include: 'path of input image directory',
    use: {
        loader: 'file-loader',
        options: {
            name: '[path][name].[ext]',
            outputPath: 'path of output image directory'
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM