目前,在我的react应用程序中,在每个组件中,我都导入了一个图像/图标,或者简单地:
const someIcon = '../../images/icon_car.png'
然后使用它。
我试图将所有资产集中到一个images.js文件中,该文件当前与/ assets位于同一文件夹中。
但是,每当我尝试在另一个文件中使用资产时,都会出现“找不到文件错误”。并且网址显然变成了“ / fonts /”(因为Webpack显然将所有图片都定位到了该文件夹中)。
so I've got images.js which is something like that:
import carIcon from './icon_car.png';
import manIcon from './icon_man.png';
const IMAGES = {
carIcon,
manIcon,
};
export default IMAGES;
// and in myComponent.jsx:
import IMAGES from '../../assets/images';
.
.
.
and then <img src={IMAGES.carIcon} /> for example for accessing the icon.
每当我尝试从另一个组件访问导入的图标时,都会得到在控制台中找不到的文件。
我的webpack.config.js:
const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = (env, options) => ({
optimization: {
minimizer: [
new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: false }),
new OptimizeCSSAssetsPlugin({}),
],
},
entry: {
'./js/app.js': ['./js/app.js'].concat(glob.sync('./vendor/**/*.js')),
},
output: {
filename: 'app.js',
path: path.resolve(__dirname, '../priv/static/js'),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
resolve: { extensions: [".js", ".jsx"] },
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true },
},
],
},
{
test: /\.(css|scss)$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader", // compiles Sass to CSS, using Node Sass by default
],
},
{
test: /\.(woff(2)?|ttf|eot|svg|png|gif)(\?v=\d+\.\d+\.\d+)?$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
},
}],
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: '../css/app.css' }),
new CopyWebpackPlugin([{ from: 'static/', to: '../' }]),
],
});
更新:
我刚刚在我的项目中注意到了另一种奇怪/报警的行为:
当我进入myComponent.jsx并导入我的资产时:
import { vehicleIcon } from'../../../static/images/icon_car.png';
当我尝试渲染vehicleIcon时,它没有显示在屏幕上!
还:console.log(vehicleIcon)==>未定义!
另一个更新: 我注意到的另一件事: 每当我在应用程序的任何组件中使用时: 有用。而且还可以,只要我愿意,我就可以保留../../../../images,并且资产仍可以识别并绘制在屏幕上。 但是当我从'../../path_to_assets ..'导入someIcon时,someIcon是未定义的! (即使我的linter批准它是正确的文件夹)
答案 0 :(得分:0)
您可以这样做
const IMAGES = {
carIcon:'icon_car.png',
manIcon:'icon_man.png',
};
export default IMAGES;
//和myComponent.jsx中:
import IMAGES from '../../assets/images';
//Usage
<img src={"path to image folder/"+IMAGES.carIcon} />