Nuxt-模块解析失败:意外字符“#" [英] Nuxt - Module parse failed: Unexpected character '#'
问题描述
为什么我在下面收到此警告:
Why do I get this warning below for:
<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
有什么想法我可以解决这个问题吗?
Any ideas how I can fix this?
推荐答案
通过查看错误的文件内容,您可以看到它是一个markdown文件.如果检查assets
文件夹,则有一个README.md
文件.这是webpack无法理解"的.
By looking at the file's content that errored out you can see that it's a markdown file. If you check your assets
folder there is a README.md
file. This is the one that webpack fails to "understand".
为什么Webpack尝试解析markdown文件?好吧,在动态需求中,您已经指定可以请求~/assets
内部的任何文件,因此webpack必须解析在那里遇到的所有文件.
Why webpack tries to parse markdown files? Well, in your dynamic require you have specified that you may request any file that is inside ~/assets
, so webpack has to parse all the files it encounters there.
您可以通过以下任一方法解决此问题:
You can fix this by either:
-
删除
README.md
文件
指定您可能需要的扩展名,以便webpack可以调整其匹配器:
Specifying which extension you may want to require, so webpack can tweak its matcher:
require( '~/assets/' + pic + '.jpg')
这是相当有限的,因为现在您只能使用jpg
图片,并且在调用该函数时必须删除扩展名.
this one is pretty limited, as now you can only use jpg
images, and you have to strip away the extension when calling the function.
使用 require.context
匹配基于RegEx的文件(在这种情况下,所有不以.md
结尾的文件)
getImgUrl(pic) {
let context = require.context('~/assets/', false, /^(?!.*\.(?:md)$).*/);
return context('./' + pic);
}
如果要使用子目录,则可能需要将第二个参数(文档中的useSubdirectories
)更改为true
.另外,您可能需要调整./
串联以获取重复的斜杠.
If you are working with subdirectories you may need to change the second argument (useSubdirectories
in the docs) to true
. Also you may need to tweak the ./
concatenation for duplicated slash.