为什么我在下面收到此警告:
<img :src="getImgUrl(post.thumbnail.src)" :alt="post.thumbnail.alt">
methods: {
getImgUrl(pic) {
return require( '~/assets/' + pic )
}
}
在终端上的警告:
Module parse failed: Unexpected character '#' (1:0) friendly-errors 16:58:06
You may need an appropriate loader to handle this file type.
> # ASSETS
|
| **This directory is not required, you can delete it if you don't want to use it.**
friendly-errors 16:58:06
@ ./assets sync ^\.\/.*$
@ ./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./pages/work/index.vue?vue&type=script&lang=js&
@ ./pages/work/index.vue?vue&type=script&lang=js&
@ ./pages/work/index.vue
@ ./.nuxt/router.js
@ ./.nuxt/index.js
@ ./.nuxt/client.js
@ multi eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client ./.nuxt/client.js
有什么办法可以解决这个问题吗?
答案 0 :(得分:1)
通过查看错误的文件内容,您可以看到它是一个markdown文件。如果您检查assets
文件夹,则会有一个README.md
文件。这是webpack无法“理解”的。
为什么Webpack尝试解析markdown文件?好吧,在动态需求中,您已经指定可以请求~/assets
内部的任何文件,因此webpack必须解析在那里遇到的所有文件。
您可以通过以下任一方法解决此问题:
删除README.md
文件
指定您可能需要的扩展名,以便webpack可以调整其匹配器:
require( '~/assets/' + pic + '.jpg')
这是相当有限的,因为现在您只能使用jpg
张图片,并且在调用该函数时必须删除扩展名。
使用require.context
,它允许您基于RegEx匹配文件(在这种情况下,所有不以.md
结尾的文件)
getImgUrl(pic) {
let context = require.context('~/assets/', false, /^(?!.*\.(?:md)$).*/);
return context('./' + pic);
}
如果您正在使用子目录,则可能需要将第二个参数(文档中的useSubdirectories
)更改为true
。另外,您可能需要调整./
的串联以获取重复的斜杠。
基于Webpack - Require.context -How to require all .js files except `_test.js` in a directory?和https://github.com/survivejs/webpack-book/issues/80#issuecomment-216068406