Rails 6 和 Highcharts

Rails 6 and Highcharts

我正在使用 Rails 6.0.0.rc1 并希望实现 lazy_high_charts gem. I installed Highcharts via Yarn 但收到以下错误:

ReferenceError: Can't find variable: Highcharts

其中指的是下面这行代码:

window.chart = new Highcharts.Chart(options);

我通过 DOM 检查了 Highcharts 是否存在,确实如此。如果我在我的 <head> 标签中添加 <script src="https://code.highcharts.com/highcharts.js"></script> 脚本,它可以正常加载,这很奇怪。任何帮助将不胜感激。

javascript/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('jquery')
require("trix")
require("@rails/actiontext")

import Highcharts from 'highcharts';
import 'bootstrap'

package.json

{
  "name": "app_name",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0-alpha",
    "@rails/actiontext": "^6.0.0-rc1",
    "@rails/activestorage": "^6.0.0-alpha",
    "@rails/ujs": "^6.0.0-alpha",
    "@rails/webpacker": "^4.0.7",
    "bootstrap": "^4.3.1",
    "highcharts": "^7.1.2",
    "jquery": "^3.4.1",
    "popper.js": "^1.15.0",
    "trix": "^1.0.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.7.1"
  }
}

Gemfile

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.3'
gem 'rails', '~> 6.0.0.rc1'
gem 'pg', '>= 0.18', '< 2.0'
gem 'puma', '~> 3.11'
gem 'sass-rails', '~> 5'
gem 'webpacker', '~> 4.0'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'image_processing', '~> 1.2'
gem 'bootsnap', '>= 1.4.2', require: false
gem 'lazy_high_charts'

group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  gem 'webdrivers'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

我找到了解决办法。添加:

window.Highcharts = Highcharts;

我的 application.js 成功了。我的图表现在正在显示。

这是我的 application.js 在 Rails 6 中使用 webpacker 的内容:

import Highcharts from 'highcharts'
import HighchartsMore from 'highcharts/highcharts-more';
import HighchartsSolidGauge from 'highcharts/modules/solid-gauge';
import HighchartsExporting from 'highcharts/modules/exporting';

window.jQuery = jQuery
window.$ = $
window.Highcharts = Highcharts;

我添加了一些扩展作为示例。

  1. 在控制台中yarn add highcharts
  2. In app/javascript/packs/application.js for Rails 6 with webpacket:
import Highcharts from 'highcharts';
require("highcharts/modules/data")(Highcharts)
require("highcharts/modules/exporting")(Highcharts)
require("highcharts/modules/offline-exporting")(Highcharts)
require("highcharts/modules/map")(Highcharts)
window.Highcharts = Highcharts;