Closed fiedl closed 4 years ago
[2020-01-26 12:23:58] fiedl@fiedl-mbp ~/rails/webpacker-engine-test master ⚡
▶ rails new main_app_with_webpacker --webpack=vue
Include the engine in the Gemfile
and install it.
# Gemfile
gem 'my_engine', path: '../my_engine'
[2020-01-26 12:41:15] fiedl@fiedl-mbp ~/rails/webpacker-engine-test/main_app_with_webpacker master ⚡
▶ bundle install
To check if the engine is loaded, try to access its module in the rails console of the main app.
[2020-01-26 12:41:21] fiedl@fiedl-mbp ~/rails/webpacker-engine-test/main_app_with_webpacker master ⚡
▶ be rails c
Running via Spring preloader in process 43702
Loading development environment (Rails 6.0.2.1)
irb(main):001:0> MyEngine
=> MyEngine
There is a pre-defined pack app/javascript/packs/hello_vue.js. To test the initial webpack setup, I'm including this pack into the main layout.
<% # app/views/layouts/application.html.erb %>
<!DOCTYPE html>
<html>
<head>
<title>MainAppWithWebpacker</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<% # include hello_vue here: %>
<%= javascript_pack_tag 'hello_vue' %>
<%= stylesheet_pack_tag 'hello_vue' %>
</head>
<body>
<%= yield %>
</body>
</html>
This adds the "Hello Vue" dynamically when accessing http://localhost:3000:
I'm switching to the hello_my_engine
pack in the application layout.
<%= javascript_pack_tag 'hello_my_engine' %>
<%= stylesheet_pack_tag 'hello_my_engine' %>
This pack just contains a small reference to the engine's js:
// app/javascript/packs/hellp_my_engine.js
import MyEngine from 'my_engine'
document.addEventListener('DOMContentLoaded', () => {
const my_engine = new MyEngine()
my_engine.hello_world()
})
How does webpack know what my_engine
is? It needs to be added to the package.json
of the main app.
I'm referring to the npm package of my_engine
with a relative path as a first attempt:
https://github.com/fiedl/webpacker-engine-test/issues/6#issuecomment-578506128
[2020-01-26 15:14:51] fiedl@fiedl-mbp ~/rails/webpacker-engine-test/main_app_with_webpacker master ⚡
▶ yarn add ../my_engine
This actually works:
I'm switching the main app to use the second engine (#2):
I'm adding the dependency on my_second_engine
to the Gemfile
and to package.json
.
Then, in the application layout:
<%= javascript_pack_tag 'hello_my_second_engine' %>
<%= stylesheet_pack_tag 'hello_my_second_engine' %>
In app/javascript/hello_my_second_engine.js
:
import MySecondEngine from 'my_second_engine'
document.addEventListener('DOMContentLoaded', () => {
const my_second_engine = new MySecondEngine()
my_second_engine.hello_world()
})
I'm running the local development environment for now (#7).
This works:
This app's javascript
import
s the node module provided by the engine.Webpack should handle the rest. https://github.com/rails/webpacker