嗨,我在一个单独的override-webpack中覆盖了create-react-app的webpack。ts文件。
我所做的是:
- 打包js文件并复制到
build/static/js
- 将css文件打包并复制到
build/static/css
- **复制/assets/img文件夹并复制到
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
文件,和NOT从我的react组件,这些图像将被忽略,(如上面所示),这就是我所寻找的,如何将它们也包含在构建文件夹中
我override-webpack。如下所示:.
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应该可以识别导入并写入文件。