嗨,我在單獨的 override-webpack.ts 檔案中覆寫了 create-react-app 的 webpack。
我做的是:
- 打包js檔案并將它們復制到
build/static/js - 捆綁css檔案并將它們復制到
build/static/css - **復制 /assets/img 檔案夾并將它們復制到
build/static/media
**并非assets檔案夾中的所有影像都被復制。用于反應組件的影像被忽略,如下所示:
<img width="34 src={${url}/img/car.svg} alt="Webpack 不會將我使用的影像復制到 React 組件中" />
語境:
所以所有的 js 和 css 檔案都被正確捆綁。
我的問題是,影像(PNG,SVG)從src/assets/img被復制到build/static/media,僅僅是用來到的那些scss檔案,不是從whithin我的反應成分,這些影像將被忽略,(正如我上面顯示),以及是我要找的,如何將它們也包含在構建檔案夾中
我的修調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="Webpack 不會將我使用的影像復制到 React 組件中" />
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。
uj5u.com熱心網友回復:
問題是,您不是在 React 中匯入使用過的影像,而只是鏈接到它們。嘗試匯入和使用影像檔案,如下所示:
import CarImage from '../../img/car.svg';
// further down in the component
<img width="34 src={CarImage} alt="Webpack 不會將我使用的影像復制到 React 組件中" />
現在 webpack 應該識別匯入并寫入檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/328927.html
標籤:javascript 节点.js 反应 网络包 webpack-4
