问题
I created a new Rails 6 project and I'm trying to install the third party javascript library Glide.js via Webpack. However, it seems like I'm missing a crucial step because it's not working.
What I've done so far:
- Install Glide.js with yarn:
yarn add @glidejs/glide
- Require Glide.js in /app/javascript/packs/application.js:
require("jquery")
require("@glidejs/glide")
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import "bootstrap"
import "../stylesheets/application"
document.addEventListener("turbolinks:load", () => {
$('[data-toggle="tooltip"]').tooltip()
$('[data-toggle="popover"]').popover()
})
- Add javascript_pack_tag in /app/views/layouts/application.html.erb:
<head>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
When I start the rails server and try to create a Glide object in the web console, I receive the error:
> new Glide({})
> ReferenceError: Glide is not defined
How can I install Glide.js successfully?
回答1:
Instead of CommonJS require
use ES6 import
import "bootstrap"
import Glide from "@glidejs/glide"
import "../stylesheets/application"
回答2:
Using ES Modules
import Glide from '@glidejs/glide'
new Glide('.glide').mount()
Here's the official doc about setup https://glidejs.com/docs/setup/
来源:https://stackoverflow.com/questions/57806349/install-glide-js-in-rails-6-with-webpack