Gatsby: 不能动态需要img吗?

创建于 2017-07-17  ·  3评论  ·  资料来源: gatsbyjs/gatsby

你好,我正在写一个博客,我想在帖子索引中列出我所有的帖子,每个帖子都有一个封面。
下面是我的代码:

 {posts.map(post => {
            return <li key={post.node.fields.slug}>
              <Link to={post.node.fields.slug}>
                <img className="news-img" src={require(`../${post.node.frontmatter.cover.relativePath}`)} />
                <h3 className="news-titles">{post.node.frontmatter.title}</h3>
                <p className="news-desc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{post.node.excerpt}</p>
              </Link>
            </li>
          }
          )}

但我收到了警告:

 warning  in ./src/pages/md/new4/new4.md

Module parse failed: /Users/magicly/development/blog/gatsby-starter-blog/src/pages/md/new4/new4.md Assigning to rvalue (1:2)
You may need an appropriate loader to handle this file type.
SyntaxError: Assigning to rvalue (1:2)
    at Parser.pp$4.raise (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp$2.checkLVal (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:1509:12)
    at Parser.pp$3.parseMaybeUnary (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:1685:24)
    at Parser.pp$3.parseExprOps (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseExpression (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseStatement (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:727:47)
    at Parser.pp$1.parseTopLevel (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:638:25)
    at Parser.parse (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:516:17)
    at Object.parse (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/acorn/dist/acorn.js:3098:39)
    at Parser.parse (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/webpack/lib/Parser.js:902:15)
    at NormalModule.<anonymous> (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/webpack/lib/NormalModule.js:104:16)
    at NormalModule.onModuleBuild (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
    at nextLoader (/Users/magicly/development/blog/gatsby-starter-blog/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /Users/magicly/development/blog/gatsby-starter-blog/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:259:5

 @ ./src/pages ^\.\/.*$

尽管有警告,页面看起来还可以,但是当我构建页面并部署时,出现了错误:

Uncaught TypeError: Cannot read property 'call' of undefined
    at t (bootstrap 29073ca…:52)
    at Object../src/components/Footer/footer.css (footer.css:1)
    at t (bootstrap 29073ca…:52)
    at Object.<anonymous> (index.jsx:5)
    at Object../src/components/Footer/index.jsx (layout-component---index-adc8f24….js:153)
    at t (bootstrap 29073ca…:52)
    at Object.<anonymous> (index.jsx:3)
    at Object../node_modules/babel-loader/lib/index.js?{"plugins":["/Users/magicly/development/blog/gatsby-starter-blog/node_modules/gatsby/dist/utils/babel-plugin-extract-graphql.js","add-module-exports","add-module-exports","add-module-exports","transform-object-assign",["transform-react-jsx",{"pragma":"Glamor.createElement"}],"babel-plugin-glamor"],"presets":["/Users/magicly/development/blog/gatsby-starter-blog/node_modules/babel-preset-react/lib/index.js","/Users/magicly/development/blog/gatsby-starter-blog/node_modules/babel-preset-es2015/lib/index.js","/Users/magicly/development/blog/gatsby-starter-blog/node_modules/babel-preset-stage-1/lib/index.js","/Users/magicly/development/blog/gatsby-starter-blog/node_modules/babel-preset-env/lib/index.js","/Users/magicly/development/blog/gatsby-starter-blog/node_modules/babel-preset-stage-0/lib/index.js","/Users/magicly/development/blog/gatsby-starter-blog/node_modules/babel-preset-react/lib/index.js"],"cacheDirectory":true}!./src/layouts/index.jsx (layout-component---index-adc8f24….js:757)
    at t (bootstrap 29073ca…:52)
    at index.jsx?8a0a:11

然后我将我的代码更改为:

 {posts.map(post => {
            const path = `../${post.node.frontmatter.cover.relativePath}`;
            return <li key={post.node.fields.slug}>
              <Link to={post.node.fields.slug}>
                <img className="news-img" src={require(path)} />
                <h3 className="news-titles">{post.node.frontmatter.title}</h3>
                <p className="news-desc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{post.node.excerpt}</p>
              </Link>
            </li>
          }
          )}

我在控制台上收到警告,
``` WARNING 编译时有 1 个警告 10:31:08

./src/pages/news/index.jsx 中的警告

关键依赖:
103:74-87 依赖的请求是一个表达式

@ ./src/pages/news/index.jsx 103:74-87

and the error on web page:

错误:找不到模块“../md/new4/cover4.png”。
http://localhost :8000/commons.js:55706:42
webpackContextResolve (webpack:/src/pages/news
^./. $:11webpackContext (webpack:/src/pages/news^./. $:8
http://localhost :8000/commons.js:7945:98
数组.map
(本国的)
索引.render
webpack:///src/pages/news/index.html jsx:21
索引.render
webpack:///~/react-proxy/modules/createPrototypeProxy.js:44
http://localhost :8000/commons.js:30838:22
测量生命周期性能
webpack:///~/react-dom/lib/ReactCompositeComponent.js:75
ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext
webpack:///~/react-dom/lib/ReactCompositeComponent.js:794

I am sure the path  '../md/new4/cover4.png' is right, because if I change code to:

{posts.map(post => {
返回


  • {post.node.frontmatter.title}


    {post.node.excerpt}




    }
    )}
    ```
    那么一切都很好。 我的环境是:
    节点:v8.1.2
    npm:v5.0.3
    盖茨比:1.2.0
    OSX 10.11.5

    谢谢~

  • 最有用的评论

    我谷歌

    the request of a dependency is an expression
    

    终于找到了这个https://webpack.github.io/docs/context.html。 这似乎是 webpack 动态要求的问题。
    将我的代码更改为

     {posts.map(post => {
                let path = `${post.node.frontmatter.cover.relativePath}`;
                path = path.slice(0, path.lastIndexOf('.'))
                return <li key={post.node.fields.slug}>
                  <Link to={post.node.fields.slug}>
                    <img className="news-img" src={require('../' + path + '.png')} />
                    <h3 className="news-titles">{post.node.frontmatter.title}</h3>
                    <p className="news-desc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{post.node.excerpt}</p>
                  </Link>
                </li>
              }
              )}
    

    现在一切正常。

    所有3条评论

    我谷歌

    the request of a dependency is an expression
    

    终于找到了这个https://webpack.github.io/docs/context.html。 这似乎是 webpack 动态要求的问题。
    将我的代码更改为

     {posts.map(post => {
                let path = `${post.node.frontmatter.cover.relativePath}`;
                path = path.slice(0, path.lastIndexOf('.'))
                return <li key={post.node.fields.slug}>
                  <Link to={post.node.fields.slug}>
                    <img className="news-img" src={require('../' + path + '.png')} />
                    <h3 className="news-titles">{post.node.frontmatter.title}</h3>
                    <p className="news-desc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{post.node.excerpt}</p>
                  </Link>
                </li>
              }
              )}
    

    现在一切正常。

    感谢@magicly编写了这个修复程序,当我从 Gatsbyv 0.x 迁移到 v1.x 时,这个问题真的让我很头疼。 对于任何偶然发现这一点的人,我想要同样的东西,但也希望文件扩展名是动态的。

    在我的情况下,在@magicly 的情况下,从事物的外观来看,我们正在为单个文章创建封面图片,路径来自 Markdown frontmatter。 对于像 Gatsby 默认入门博客这样的项目的上下文,您可能会有这样的一些内容:

    ---
    title: The title of the post
    featured_image: ./teaser.jpg
    ---
    

    然后在列出所有文章的索引页面上的 GraphQL 查询中,您将希望包含featured_image@magicly称为cover )。

    frontmatter {
      title
      featured_image {
        name
        ext
        relativePath
      }
    }
    

    现在您可能想要遍历所有帖子,并在索引页面上显示标题和特色图片。 在您的 React 组件中,您可能会执行以下操作:

    // …
    
    // Create a new require context for Webpack
    const requireFeatureImage = require.context(
      `./../pages/portfolio/`, // Don’t make this a variable
      true, // Whether or not to check subdirectories
      /^.*\.(svg|png|gif|jpg|jpeg|webp|)$/ // Rough regex for extensions, maybe change this for your use case?
    )
    
    return (
      <ol>
        {pages.map(function(page, i) {
          let path = page.node.frontmatter.featured_image.relativePath
          let imgPath = `./${path.split('portfolio/')[1]}`
    
          return (
            <li key={`Item_${page.node.fields.slug}`}>
              <Link to={page.node.fields.slug}>
                <img src={requireFeatureImage(imgPath)} />
                <h2>
                  {page.node.frontmatter.title}
                </h2>
              </Link>
            </li>
          )
        })}
      </ol>
    )
    

    require.context with Webpack 2 的文档更详细地解释了设置,但并没有真正展示我不认为的这样的用例。 无论如何,它似乎不是 Gatsby 问题,而是一个相当普遍的模式,需要(抱歉)一些关于 Webpack 的相当具体的知识。

    @KyleAMathews这是您可能对我为文档扩展感兴趣的内容吗? 或者对于我错过的这类事情有没有一个例子/更好的方法? 谢谢!

    本教程的第 5 部分将介绍这一点,但与此同时,请查看 www 和 gatsbygram,例如https://github.com/gatsbyjs/gatsby/blob/66e86d4b45dad70bfcf78861002e0108863f7985/www/src/pages/index.js#L209

    如果您安装https://www.gatsbyjs.org/packages/gatsby-transformer-sharp/ ,则可以通过 graphql 查询 frontmatter 中的链接图像。

    此页面是否有帮助?
    0 / 5 - 0 等级

    相关问题

    Oppenheimer1 picture Oppenheimer1  ·  3评论

    jimfilippou picture jimfilippou  ·  3评论

    kalinchernev picture kalinchernev  ·  3评论

    signalwerk picture signalwerk  ·  3评论

    benstr picture benstr  ·  3评论