【问题标题】:Set publicpath in ReactJs project with Webpack 4使用 Webpack 4 在 ReactJs 项目中设置公共路径
【发布时间】:2019-11-30 04:15:07
【问题描述】:

我正在使用带有 ReactJs 项目的 webpack 4。我的项目目录:

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

所以,我正在尝试在我的 index.html 文件中使用 public 文件夹中的 css、js 和图像。但我无法从public 文件夹加载图像。所以,我尝试在 webpack 配置中为这个文件夹设置输出 publicPath。

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

结果是Cannot GET / 我所有的 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,
          },
        },
      },
    },
  };
};

我的目的是什么配置?并正确运行 React 项目?谢谢

【问题讨论】:

标签: javascript reactjs webpack


【解决方案1】:

您正在尝试做的事情非常hacky,不安全,而且不是应该做的事情。您想要提供给用户的任何内容都应该在dist 文件夹中。

事实并非如此,这并不意味着您使用 webpack 错误。

您应该导入图像并像这样使用它:

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;

还有一个图片加载器——例如:

{
    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'
        }
    }
}

【讨论】:

    猜你喜欢
    • 2016-09-08
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2018-07-29
    • 2021-05-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多