Ruby on rails webpacker can't find images under asset_pack_path

后端 未结 5 1564
野的像风
野的像风 2021-02-06 15:16

I have a problem with including images in my views using Ruby on Rails Webpacker. When i try to insert image in my view using html img tag and asset_pack_path i got an error. My

相关标签:
5条回答
  • 2021-02-06 15:35

    I had an issue with getting images to show up in Rails 6. I did this:

    Add image to

    assets/custom_folder/img_filename.file_extension
    

    Uncomment two lines in javascript/packs/application.js

    const images = require.context('../images', true)
    const imagePath = (name) => images(name, true)
    

    Then add your image to your erb file using this: (I had an index.html.erb view file)

    <%= image_tag("custom_folder/file_name.file_extension")%>
    

    This worked for me, hope it helped.

    Check out this link

    0 讨论(0)
  • 2021-02-06 15:40

    It looks like the path is not in the manifest file.

    In Rails 6 there are two commented lines in application.js. Regardless of what rails version you're running just make sure you add them in:

    const images = require.context('../images', true)
    const imagePath = (name) => images(name, true)
    

    Alternatively, you can force the images to be added to the manifest by moving your folder inside packs, eg. packs/images. The path would change though to media/images/your-file.png.

    For seeing if the path exists or not, I found it easier to just lookup it up from ruby directly:

    Webpacker.manifest.send(:data).keys.grep /logo/
    
    0 讨论(0)
  • 2021-02-06 15:43

    For accessing images handled by Sprockets, add this to your your_file_name.js.erb file:

    <% helpers = ActionController::Base.helpers %>
    const railsImagePath = "<%= helpers.image_path('your_image.png') %>"
    
    0 讨论(0)
  • 2021-02-06 15:44

    My images are located in /app/assets/images.

    Firstly add app/assets to resolved_paths: ['app/assets'] in webpacker.yml

    And then you can use the image in your JS like so:

    <img src='~images/logo.png' />

    in CSS:

    <style lang='sass'>
    #app
      background: url('~images/logo.png')
    </style>
    
    0 讨论(0)
  • 2021-02-06 15:56
    1. Place your images in app/javascripts/images

    2. Put following code in application.js At TOP of the file.

      // top of packs/application.js

      const importAll = (r) => r.keys().map(r)

      importAll(require.context('../images', false, /\.(png|jpe?g|svg)$/));

    3. This will load all images from images folder and then it should be available in manifest for you to pick up using asset_pack_path

    4. In your erb files, use like <%= asset_pack_path 'media/images/image_name.png' %>

    -- Read this for more details https://github.com/rails/webpacker/issues/1839

    0 讨论(0)
提交回复
热议问题