[英]How to avoid can't find module
I have reactjs
script which use .jpg
我有使用
.jpg
reactjs
脚本
However jpg filename is dynamically changed.但是 jpg 文件名是动态更改的。
const img_require = require(id + ".jpg");
it works well when file exists, but when there is not file,当文件存在时它工作得很好,但是当没有文件时,
throwing error like this below在下面抛出这样的错误
Error: Cannot find module './12.jpg'
I want to avoid this error message and use dummy.jpg
.我想避免此错误消息并使用
dummy.jpg
。
But this code doesn't work on browser side(of course)但是这段代码在浏览器端不起作用(当然)
fs = require('fs')
if (fs.exitsSync('./12.jpg')){
// ok
}else {
const img_require = 'dummy.jpg';
}
Is there any idea??有什么想法吗??
You can use try-catch block for require file like this :您可以像这样对需要文件使用 try-catch 块:
I am not expert in react but this might be basic hack 😅.我不是反应方面的专家,但这可能是基本的 hack 😅。
var fs;
try {
fs = require(id + ".jpg")
} catch (error) {
fs = require("dummy.jpg")
}
One more way to handle error that is provided by require.js
using ErrorCallback使用ErrorCallback处理
require.js
提供的错误的require.js
方法
here is the fallback answer for module load.这是模块加载的后备答案。
Catching module loading errors and processing them 捕获模块加载错误并处理它们
require([path], function(content){
//need to catch errors as this will not be called;
}, function (err) {
//display error to user
});
const dynamicid = id || 'dummy'
const img_require = require(`${dynamicid} + .jpg`);
var dynamicId = id ? id : 'dummy'
var img = require(`${dynamicId} + .jpg`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.