嗨,我在单独的 override-webpack.ts 文件中覆盖了 create-react-app 的 webpack。
我要做的是:
build/static/js
build/static/css
build/static/media
**并非来自
assets
的所有图片文件夹被复制。那些用于 react 组件的文件夹被忽略,如下所示:<img width="34 src={${url}/img/car.svg} alt="car" />
上下文:所以所有的 js & css 文件都被正确捆绑了。
我的问题是 图片(png,svg) 来自
src/assets/img
被复制到 build/static/media
, 只是用于 scss
的那些文件和 不是 从我的 react 组件 ,这些图像被忽略,( 如我在上面显示的 ),这就是我要寻找的,如何将它们也包含在构建文件夹中 我的 override-webpack.ts 是这样的: .
var configurator = {
paths(paths) {
// paths
},
webpack(config, env) {
//if stage, prod, dev
bundleSass()
addMedia()
overrideOutput()
return config;
}
}
module.exports = configurator;
// overrride the publicPath of the bundles, so to have it into index.html
function overrideOutput(config) {
config.output.filename = 'static/js/[name].[hash:8].js';
config.output.chunkFilename = 'static/js/[name].[hash:8].chunk.js';
config.output.publicPath = `http://www.something.com/`; // this is added into index.html
}
// copy images to build/static folder, i was hoping to copy the fonts as well but it does not..
// this functionality ONLY copies the images that are called into the css files,
// it IGNORES the images that used into react components,
// like:
// <img width="34 src={`${url}/img/user.svg`} alt="user" />
function addMedia(config){
const media = {
test: /\.(woff(2)?|ttf|eot|svg|png)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'static/media', // by default it creates a media folder
}
}
]
};
config.module.rules.push( media ); // push the rule to the module array
}
// bundle scss files
function bundleSass(config) {
// add rule for the sass-loader, so to bundle the scss files
}
为什么没有将 react 组件内部的图像复制到 build/static/media
的任何建议很受欢迎。
最佳答案
问题是,您没有在 React 中导入使用过的图像,而只是链接到它们。
尝试像这样导入和使用图像文件:
import CarImage from '../../img/car.svg';
// further down in the component
<img width="34 src={CarImage} alt="car" />
现在 webpack 应该识别导入并写入文件。
关于javascript - Webpack 不会将我使用的图像复制到 react 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69658519/