I am trying to load images from a local folder using the src=»» from the img tag but I want to load them using the backend. The frontend already has the relative path which is «../assets/imgs/» the backend just has the name and extension ex) «1.png». Thing is that it does work but I’m getting error messages.
This is causing me an issue
<img width=100px height=100px :src="getIconPath(`${user.icon}`)"/>
here is the function that gets called
methods: {
getIconPath(iconName) {
return iconName ? require("../assets/imgs/" + iconName) : ''
}
Here are both the error messages I am getting on the console
[Vue warn]: Error in render: "Error: Cannot find module './undefined'"
found in
---> <Profile> at src/components/profile.vue
<Navbar> at src/components/navbar.vue
<Main> at src/main.vue
<Root> vue.runtime.esm.js:619
Error: "Cannot find module './undefined'"
webpackContextResolve .*$:13
webpackContext .*$:8
getIconPath profile.vue:74
render profile.vue:12
VueJS 43
<anonymous> main.js:31
js app.js:1415
__webpack_require__ app.js:785
fn app.js:151
1 app.js:1488
__webpack_require__ app.js:785
checkDeferredModules app.js:46
<anonymous> app.js:861
<anonymous>
I found very little resources to help out but many of them have said that required fixes their issues. So far I tried moving it to a different folder, moving the require as a function method, using absolute path, using v-attr, and binding it without require. Still I haven’t had any luck getting rid of the error message. Here is another link of someone else having the same issue as me but I still couldn’t figure out how they fixed it.
https://forum.vuejs.org/t/how-to-fix-the-console-log-error-when-using-require-method-to-bind-an-img-src/77979
I would very much appreciate the help!! I’ve been stuck for many hours on this and I can’t seem to find a helpful solution. If this isn’t a good way to go about loading images from the backend feel free to suggest any other alternative ways to do so. Thank You!
🐛 bug report
Chrome throw Error when import()
dynamic import more than ONE vue components, though vue components render successfully.
🎛 Configuration (.babelrc, package.json, cli command)
.babelrc
{ "presets": ["env"], "plugins": ["transform-runtime"] }
package.json
"devDependencies": { "@vue/component-compiler-utils": "^1.3.1", "babel-core": "^6.26.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-env": "^1.6.1", "vue-hot-reload-api": "^2.3.0", "vue-template-compiler": "^2.5.16" }
🤔 Expected Behavior
No Error reports.
😯 Current Behavior
Both vue components rendered successfully.
But there was an Error.
Uncaught (in promise) Error: Cannot find module ‘undefined’
at newRequire
💻 Code Sample
index.js
(async ()=>{ new Vue({ components:{ 'the-header': () => import('./components/Header.vue'), 'the-home': () => import('./components/Home.vue') } }).$mount('#app') })()
🌍 Your Environment
Software | Version(s) |
---|---|
Parcel | 1.8.1 |
Node | 8.9.1 |
npm/Yarn | npm 5.5.1 |
Operating System | macOS |
Я пытаюсь загрузить изображения из локальной папки, используя src = «» из тега img, но я хочу загрузить их, используя серверную часть. У внешнего интерфейса уже есть относительный путь, который является «../assets/imgs/», у внутреннего интерфейса есть только имя и расширение ex) «1.png». Дело в том, что он работает, но я получаю сообщения об ошибках.
Это вызывает у меня проблему
<img width=100px height=100px :src="getIconPath(`${user.icon}`)"/>
Вот функция, которая вызывается
methods: {
getIconPath(iconName) {
return iconName ? require("../assets/imgs/" + iconName) : ''
}
Вот оба сообщения об ошибках, которые я получаю на консоли.
[Vue warn]: Error in render: "Error: Cannot find module './undefined'"
found in
---> <Profile> at src/components/profile.vue
<Navbar> at src/components/navbar.vue
<Main> at src/main.vue
<Root> vue.runtime.esm.js:619
Error: "Cannot find module './undefined'"
webpackContextResolve .*$:13
webpackContext .*$:8
getIconPath profile.vue:74
render profile.vue:12
VueJS 43
<anonymous> main.js:31
js app.js:1415
__webpack_require__ app.js:785
fn app.js:151
1 app.js:1488
__webpack_require__ app.js:785
checkDeferredModules app.js:46
<anonymous> app.js:861
<anonymous>
Я нашел очень мало ресурсов, чтобы помочь, но многие из них сказали, что требуется исправить их проблемы. До сих пор я пытался переместить его в другую папку, переместив require как метод функции, используя абсолютный путь, используя v-attr, и привязав его без необходимости. Тем не менее мне не удалось избавиться от сообщения об ошибке. Вот еще одна ссылка на кого-то, у кого такая же проблема, как у меня, но я все еще не мог понять, как они ее исправили.
https://forum.vuejs.org/t/how-to-fix-the-console-log-error-when-using-require-method-to-bind-an-img-src/77979
Я был бы очень признателен за помощь !! Я застрял на этом много часов и не могу найти полезного решения. Если это не лучший способ загрузки изображений из серверной части, не стесняйтесь предлагать любые другие альтернативные способы сделать это. Благодарю вас!
1 ответ
Лучший ответ
Я собираюсь предположить здесь и сказать, что user
заполняется данными асинхронно. Бьюсь об заклад, у вас есть что-то подобное в ваших исходных данных или в хранилище
{
user: {}
}
Проблема здесь в том, что user.icon
равно undefined
, по крайней мере, в течение некоторого периода времени. Если вы без нужды конвертируете это в строку с
getIconPath(`${user.icon}`)
Преобразует undefined
в строку "undefined"
(потому что JavaScript такой забавный), отсюда и ваше сообщение об ошибке. Простое решение — не использовать строковый шаблон, т. Е.
getIconPath(user.icon)
Чтобы избежать подобных проблем, я бы вместо этого использовал вычисляемое свойство для разрешения импорта изображений. Это более эффективно, чем выполнение метода в шаблоне, которое происходит каждый тик .
computed: {
userWithIcon () {
return {
...this.user,
icon: this.user.icon && require(`../assets/imgs/${this.user.icon}`)
}
}
}
И в вашем шаблоне
<img width="100px" height="100px" :src="userWithIcon.icon">
3
Phil
29 Апр 2020 в 04:14
I just encountered this error while navigating to different links using NextJs’s Link Component; Once this error showed up, I couldn’t access any pages until I restarted the npm run build command, and everything worked properly again.
However, I can’t figure out what caused this error and I wanted to make sure this doesn’t happen in my production app. Does anyone have an idea what might have caused this error?
Error: Cannot find module './undefined'
Require stack:
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/.next/server/webpack-runtime.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/.next/server/pages/_document.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/server/require.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/server/load-components.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/build/utils.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/build/output/store.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/build/output/index.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/cli/next-dev.js
- /Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/bin/next
at Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
at mod._resolveFilename (/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/build/webpack/require-hook.js:183:28)
at Module._load (node:internal/modules/cjs/loader:804:27)
at Module.require (node:internal/modules/cjs/loader:1022:19)
at require (node:internal/modules/cjs/helpers:102:18)
at __webpack_require__.f.require (/Users/tylerkim/Documents/GitHub/scraft/scraft-app/.next/server/webpack-runtime.js:233:28)
at /Users/tylerkim/Documents/GitHub/scraft/scraft-app/.next/server/webpack-runtime.js:160:40
at Array.reduce (<anonymous>)
at __webpack_require__.e (/Users/tylerkim/Documents/GitHub/scraft/scraft-app/.next/server/webpack-runtime.js:159:67)
at Array.map (<anonymous>) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/.next/server/webpack-runtime.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/.next/server/pages/_document.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/server/require.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/server/load-components.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/build/utils.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/build/output/store.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/build/output/index.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/cli/next-dev.js',
'/Users/tylerkim/Documents/GitHub/scraft/scraft-app/node_modules/next/dist/bin/next'
]
}
error - Error: Cannot find module './undefined'
✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
“Error: cannot find module” occurs when you try to load a non-existant module in Node – Either via ESM (ECMAScript Modules) or CommonJS module systems.
The error usually looks like this in the console:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module '/var/www/scripts/app.js'
Enter fullscreen mode
Exit fullscreen mode
Why does «Error: cannot find module» occur?
The error «cannot find module» might happen if you’re trying to:
- Import a third-party package you haven’t installed yet (with
npm
oryarn
). - Import a local module, but the path is wrong.
- Run a node script in the terminal, but the script doesn’t exist (or path is wrong).
- Use node standard libraries with TypeScript, but you haven’t installed the
@types/node
package. - The module’s
package.json
has a main field pointing to an entry file that doesn’t exist.
Before anything, let’s review what a module is and how module systems work in a high level (Or jump to the solutions).
The module system: Modules are the building blocks of an application. Node implements ESM and CommonJS (the default one) module systems to let you organize your code as reusable components.
With modules, you can only expose the public interface of your components and keep the internal functionalities private. This is done by using a module.exports
(CommonJS modules) or export
(ES Modules).
The following code is an example of a module, which has a function to determine whether a number is odd or not:
// math.js
function isOdd(number) {
return number % 2 !== 0
}
// Make isOdd available to other scripts (and other modules)
module.exports = isOdd
Enter fullscreen mode
Exit fullscreen mode
And here’s how we import it into another script called index.js
:
// index.js
const add = require('./isodd.js')
console.log(isOdd(3))
// output: true
Enter fullscreen mode
Exit fullscreen mode
All the modules you use have an ESM or CommonJS export declaration.
How do module systems find modules?
If the identifier passed to require()
or import()
is a reference to a file (it starts with /
, ../
, ./
, etc.) in your filesystem, Node will load it from the respective path. Otherwise, it looks it up in the installed modules — inside the node_modules
directory.
If the module isn’t found, it raises the «Cannot find module» error.
How to fix the «Cannot find module» error in Node.js?
There are several scenarios this error can happen; Let’s explore each.
Third-party packages: If you try to import a third-party module and get this error (and you’re sure the spelling is correct), you probably haven’t installed the package yet.
Imagine this is the code:
//index.js
const axios = require('axios');
// Make an HTTP request with Axios
Enter fullscreen mode
Exit fullscreen mode
If I run this on my machine, I’ll get the «Cannot find module» error.
And that’s because I haven’t installed it yet. So in my project directory (where my package.json
resides), I’d have to install axios
package with npm
or yarn
like so:
npm install axios
Enter fullscreen mode
Exit fullscreen mode
Local modules: Imagine you have a set of utility functions kept in a JavaScript file named utils.js
. You want to import a function called getUrl()
from this utils.js
into your script:
// index.js
const { getUrl } = require('utils')
// Do something here ...
Enter fullscreen mode
Exit fullscreen mode
But when you run npm run build
, the build fails:
ERROR in ./app/index.js 30:0-30
Module not found: Error: Can't resolve 'utils' in '/var/www/app'
Enter fullscreen mode
Exit fullscreen mode
In this case, since utils
isn’t a reference to a local file, my bundler (Webpack) assumes it’s inside a node_modules
directory. The build fails as the utils module isn’t an installed package.
So what I need to do here is to make it an absolute path by adding ./
to my identifier:
// index.js
const { getUrl } = require('./utils.js')
// Do something here ...
Enter fullscreen mode
Exit fullscreen mode
Problem solved.
Sometimes the error occurs because the letter casing is off. File names on Mac and Windows are case-insensitive by default; This means ./Utils
and ./utils
both work on Mac and Windows (where you develop the app). However, it’ll break on a Linux file system where filenames are case-sensitive.
Running a node script: Another scenario reported by developers is when you run a script with the node command. However, the respective file can’t be located — probably owing to a typo in the name or path.
So always double-check that the path is correct and the script exists. You can always take advantage of the terminal’s autocomplete feature by typing the initial letters and pressing the tab to let it complete the path for you.
node ./scriptName.js
Enter fullscreen mode
Exit fullscreen mode
Node and TypeScript: If you’re coding in TypeScript and you’re importing a built-in Node module like fs
, you might get a «Cannot find module ‘fs'» error too.
You can fix the issue by installing @types/node
:
npm install @types/node --save-dev
Enter fullscreen mode
Exit fullscreen mode
Even though all packages in node_modules/@types
(of any enclosing folder) are included in your compilation. However, it’s worth ensuring node is added under compileOptions.types
:
tsconfig.json
{
compilerOptions: {
types: [node, jest, express]
}
}
Enter fullscreen mode
Exit fullscreen mode
Missing entry file in package.json: Each module has an entry file named index.js
(by default) unless it’s changed in the module’s package.json
via the main
field.
{
name: utils
}
Enter fullscreen mode
Exit fullscreen mode
If you decide to change the main
field to another entry file (e.g., main.js
), you must ensure the file exists. Or if you rename or relocate that file in the future, remember to update the package.json
too.
Missing entry file in package.json
has been reported by several users on Stackoverflow.
Importing a module from the global node_modules
or a separate directory: Sometimes you might have to use a globally-installed package in your development environment.
If you try to load a globally-installed module in your project, you might get the «Cannot find module» error.
A workaround to this problem is using the npm link
command. If the package is installed globally, all you need to do is run the following command while in your project directory:
npm link package-name
As a result, npm will create a symbolic link from the globally installed package name to the node_modules
directory of your project — as if you’ve installed it with npm install package-name
.
If the module you want to use is a local file residing somewhere in your file system other than the global node_modules
(e.g., a module you’re developing), you’ll have to do it in a two-step process:
First step: In the terminal, you need to change the directory to where the module resides and run the npm link
(without any parameter). As a result, a symlink is created in the global node_modules that links to your local package.
npm link
Enter fullscreen mode
Exit fullscreen mode
Second step: After that, you change the directory to your project directory (where you want to import the module) and run the following command:
npm link package-name
Enter fullscreen mode
Exit fullscreen mode
This will create a symbolic link from the globally installed package name to the node_modules
directory of your project.
Now, you can use the package as if it’s an installed third-party package.
What if the problem persists?
If none of the above solutions worked for you, maybe you’re dealing with corrupted or incomplete installations. In that case, you can take the following steps:
Delete node_module
directory:
rm -rf node_modules
Enter fullscreen mode
Exit fullscreen mode
Delete package-lock.json
:
rm -f package-lock.json
Enter fullscreen mode
Exit fullscreen mode
Clear the npm cache:
npm cache clean --force
Enter fullscreen mode
Exit fullscreen mode
Install the packages again:
npm install
Enter fullscreen mode
Exit fullscreen mode
This will make a clean install of all the dependencies listed in your package.json
file.
I hope these solutions help you fix your code.
Thanks for reading.
❤️ You might like:
- TypeError: map is not a function in JavaScript in JavaScript (Fixed)
- Add commas to numbers in JavaScript (Explained with examples)
- SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)
- How to fix «ReferenceError: document is not defined» in JavaScript
- Label htmlFor Property Explained
Я пытаюсь отправить серию объектов, находящихся в массиве, дочернему компоненту с помощью v-for, но когда я пытаюсь получить к ним доступ из дочернего компонента, он сообщает мне, что свойства не определены.
Я использую Quasar Framework на самом деле
Вот как я передаю данные:
<div class = "row justify-center">
<foo
v-for = "brand in brands"
:key = "brand.id"
:brand = "brand"
></foo>
</div>
<script>
import foo from "src/components/foo.vue";
export default {
components: {
foo
},
data() {
return {
brands: []
};
},
methods: {
async getData() {
let x = await get.getData();
this.brands = x.data;
console.info(this.brands);
}
},
mounted() {
this.getData();
}
};
</script>
Brands — это массив, который получает два объекта из запроса, сделанного в локальную базу данных, который я уже подтвердил, что он правильно получает данные.
А это файл компонента и то, как я пытаюсь получить свойства:
<q-card class = "my-card" flat bordered>
<q-img
:src = "require(`../assets/${brand.img}`)"
:alt = "brand.img + ' Logo'"
/>
<div class = "text-h5 q-mt-sm q-mb-xs">{{ brand.name }}</div>
<div class = "text-caption text-grey">
<p>
{{ brand.price }}
</p>
</div>
<script>
export default {
name: "foo",
props: ["brand"],
data() {
return {
expanded: false
};
},
};
</script>
Но когда я пытаюсь выполнить код, я получаю следующую ошибку:
Error in render: «Error: Cannot find module ‘./undefined’
Я знаю один способ заставить его работать, и это создать свойство для каждого значения объекта, например:
<component
v-for = "brand in brands"
:key = "brand.id"
:name = "brand.name"
:price = "brand.price"
></component>
Но я не думаю, что это правильный способ сделать это …