Turbo.visit('/') 在 Rails 6.1.3 中无法使用 Webpacker

Turbo.visit('/') not working with Webpacker in Rails 6.1.3

我正在使用 webpacker 在 Rails 6.1.3 应用程序中设置 Turbo。似乎它应该是 运行,除了一个问题。我无法在我的 js 文件中引用它:

// app/javascript/javascripts/shared.js

Turbo.visit('/');

在我的控制台中引发错误:

Uncaught ReferenceError: Turbo is not defined
    at HTMLDocument.<anonymous> (shared.js:4)
    at HTMLDocument.dispatch (jquery.js:4670)
    at HTMLDocument.elemData.handle (jquery.js:4490)
    at dispatch (turbo.es2017-esm.js:387)
    at Session.notifyApplicationAfterPageLoad (turbo.es2017-esm.js:4822)
    at Session.pageBecameInteractive (turbo.es2017-esm.js:4718)
    at PageObserver.pageIsInteractive (turbo.es2017-esm.js:3880)
    at HTMLDocument.PageObserver.interpretReadyState (turbo.es2017-esm.js:3840)

有什么想法吗?

这是我的配置:

// app/javascript/packs/application.js

import Rails from "@rails/ujs"
import Turbo from "@hotwired/turbo"
import "jquery"
import "bootstrap"
import "../stylesheets/application"
window.bootstrap = require('bootstrap/dist/js/bootstrap.bundle.js')
Rails.start()
// config/webpack/environment.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')

environment.plugins.prepend(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Rails: '@rails/ujs',
    Popper: ['popper.js', 'default']
  })
)

module.exports = environment

// app/javascript/javascripts/shared.js
import Turbo from "@hotwired/turbo"
Turbo.visit('/');

import 不会创建在您的文件之间共享的全局。相反,它将一个模块导入当前范围。每个文件都是它自己的范围。

参见:

似乎这是使它起作用的设置:

import Rails from "@rails/ujs"
import { Turbo } from "@hotwired/turbo-rails"
window.Turbo = Turbo
Rails.start()

添加 window.Turbo 使其在 application.js 的范围之外可用。