【问题标题】:Nuxt - Module parse failed: Unexpected character '#'Nuxt - 模块解析失败:意外字符“#”
【发布时间】:2019-07-18 02:56:09
【问题描述】:

为什么我会收到以下警告:

<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

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: webpack vuejs2 assets nuxt.js


    【解决方案1】:

    通过查看出错的文件内容,您可以看到它是一个降价文件。如果您检查您的assets 文件夹,则有一个README.md 文件。这是 webpack 无法“理解”的。

    为什么 webpack 会尝试解析 markdown 文件?好吧,在您的动态 require 中,您已指定您可以请求 ~/assets 内的任何文件,因此 webpack 必须解析它在那里遇到的所有文件。

    您可以通过以下任一方式解决此问题:

    • 删除README.md 文件

    • 指定您可能需要的扩展,以便 webpack 可以调整其匹配器:

      require( '~/assets/' + pic + '.jpg')

      这个很有限,因为现在你只能使用jpg图片,调用函数时必须去掉扩展。

    • 使用require.context,它允许您匹配基于正则表达式的文件(在这种情况下,所有.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的函数

    【讨论】:

    • 感谢您的回答!第二种选择可能是最不实用的。但是对于第三个选项Cannot find module './/images/sample-1.jpg',我得到了这个错误。我的图片来源类似于src: '/images/sample-1.jpg'
    • 应该设置为true - require.context('~/assets', true, /^(?!.*\.(?:md)$).*/)
    猜你喜欢
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2017-04-04
    • 2019-05-20
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多