【发布时间】: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 项目?谢谢
【问题讨论】:
-
您可以阅读有关使用公用文件夹的指南。 facebook.github.io/create-react-app/docs/…
-
嗨@TienDuong,你看我的项目没有使用
create-react-app,你为什么给我这个指南?
标签: javascript reactjs webpack