Rendering js from a Rails controller with webpacker

前端 未结 2 941
南笙
南笙 2021-02-05 18:11

Just replaced the js pipeline in my Rails app with webpacker.

Most things work correctly, however controllers that render js no longer work as expected.

相关标签:
2条回答
  • 2021-02-05 18:39

    Figured it out thanks to this wonderful article!

    Use expose-loader to expose key libraries to vanilla JavaScript sprinkled throughout your app.

    1) Install dependency,

    yarn add expose-loader --dev
    

    2) Configure config/webpack/environment.js,

    const { environment } = require('@rails/webpacker');
    
    environment.config.merge({
      module: {
        rules: [
          {
            test: require.resolve('jquery'),
            use: [{
              loader: 'expose-loader',
              options: '$'
            }, {
              loader: 'expose-loader',
              options: 'jQuery'
            }]
          },
          {
            test: require.resolve('rails-ujs'),
            use: [{
              loader: 'expose-loader',
              options: 'Rails'
            }]
          }
        ]
      }
    });
    
    module.exports = environment;
    
    0 讨论(0)
  • 2021-02-05 18:48

    I had a similar problem where I had undefined $ on the string $("#element").html(

    My configuration is similar to yours I solved by exposing at the end of the file pack/application.js

    windows.jQuery = jQuery
    window.$ = $
    
    0 讨论(0)
提交回复
热议问题