首页 > 解决方案 > Webpack 图像加载器和 Rails

问题描述

我正在使用 Rails 6 和 webpack 在前端运行 react 并且在让图像出现在我的 react 组件上时遇到问题。

我将 Gulp 任务与 webpack 结合使用来监视和编译文件。这是我的任务的样子:

function generateBundle(dev)
{
  log('bundling dev');
  return gulp.src([paths.js.boot])
    .pipe(plumber())
    .pipe(webpack_stream({
      watch: dev,
      mode: dev ? 'development' : 'production',
      entry: ['babel-polyfill', './app/frontend/javascripts/boot.js'],
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
            }
          },
          {
            test: /\.(png|jpe?g|gif)$/i,
            exclude: /node_modules/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[name].[ext]'
                }
              },
            ],
          },
        ]
      },
      devtool: dev ? "inline-source-map" : "source-map",
      output: {
        filename: 'bundle.js'
      },
      plugins: dev ? [
          new webpack.DefinePlugin({
            'process.env': {
              NODE_ENV: JSON.stringify('development')
            }
          })
        ] : [
          new webpack.DefinePlugin({
            'process.env': {
              NODE_ENV: JSON.stringify('production')
            }
          }),
          new webpack.optimize.UglifyJsPlugin({
            sourceMap: true
          })
        ]
    }, webpack))
    //.on('error', onError)
    .pipe(chmod(0o755))
    .pipe(gulp.dest(path.join(__dirname, 'app', 'assets', 'javascripts')));
}

我有一个图像放在我的app/frontend/images/目录中,我可以确认 webpack 正在选择并编译这个图像。这是吞咽输出:

[12:01:08] Using gulpfile ~/workspace/core_react/gulpfile.js
[12:01:08] Starting 'watch'...
[12:01:08] Starting 'watch-components'...
[12:01:08] Starting '<anonymous>'...
[12:01:08] Starting 'watch-components-for-application'...
[12:01:08] bundling dev
[12:01:12] Version: webpack 4.41.1
Built at: 2020-01-03 12:01:12
        Asset      Size  Chunks             Chunk Names
PulseLogo.png  17.9 KiB          [emitted]
    bundle.js  7.44 MiB    main  [emitted]  main
Entrypoint main = bundle.js
[12:01:12] webpack is watching for changes

当我在组件中导入图像时,我收到来自 Rails 的 406 错误。这是我的组件:

import React from 'react';
import PulseLogo from '../../images/PulseLogo.png';

class Image extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return <img src={PulseLogo} />
  }
}

我收到的控制台错误:GET http://localhost:3000/PulseLogo.png 406 (Not Acceptable)

服务器日志错误:

ActionController::UnknownFormat (DashboardController#index is missing a template for this request format and variant.

request.formats: ["image/png"]
request.variant: []):

这是我的控制器:

class DashboardController < ApplicationController
  def index
  end
end
class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end

我的路线文件:

Rails.application.routes.draw do

  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root to: 'dashboard#index'
  devise_for :users, {skip: :sessions, class_name: 'User' }

  namespace :api, defaults: {format: :json} do
    mount_devise_token_auth_for 'User', at: 'auth', skip: [:omniauth_callbacks]

    resources :users
  end

  get '*path', to: 'dashboard#index', constraints: ->(request) do
    !request.xhr?
  end
end

我知道 Rails 错误意味着我没有处理图像的请求格式,但我似乎找不到解决方法。任何人都可以指导我处理这个问题的最佳方法吗?

谢谢!

标签: javascriptruby-on-railsreactjswebpack

解决方案


推荐阅读