2
votes

I've added the webpacker gem, bundled, installed and edited all my javascript_include tags to javascript_pack.

What happens with the existing javascript? I have lots of it under app/assets/javascripts and vendor/assets/javascripts. It doesn't seem to pick it up automatically.

Some of this javascript is required into application.js.erb and some other files load directly into various parts of the application, eg:

app/assets/javascripts/application.js.erb # linked to from application layout
//= require global
//= require bootstrap
//= require moment
//= require websockets
//= require init

Then I also have:

app/assets/javascripts/users.js
//= require table
//= require form
//= require sync
//= require controllers/users/index

Some of these files are small Vue apps, I've placed their templates under Rails views. Now after this webpacker business I have app/assets/javascripts (which contains all my actual code but is ignored), then app/javascript which I don't know what it is, and app/javascripts where I'm supposed to put my Vue apps. Or the other way around. Or something.

How do I get all this to work with webpacker? None of the tutorials I've found cover migrating existing code to webpacker and to be honest I don't understand much from all those javascript snippets they just dump there but don't explain what it actually does and how.

1

1 Answers

1
votes

By default, adding webpack doesn't change anything. For example, if you leave javascript_include_tag 'application' in your layout, it will continue to work the same as it did before adding webpack.

The files in the javascript/packs folder are entry points for javascript. If you are doing a single page app, you will likely have a single pack like application.js which boots up your entire application. If you are doing a conventional app, you will likely have a main application.js file that loads all global scripts, plus other page or component level scripts like settings.js or calendar.js. These scripts are loaded with javascript_pack_tag 'application'.

If you move your files out of the assets folder into the javascript folder you can then add them to your pack file like so:

import 'global';
window.$ = window.jQuery = require('jquery');
import 'bootstrap';
import 'moment';
import 'websockets';

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('do init stuff here');
    // use bootstrap here
});