David Cruwys
David Cruwys

Reputation: 6842

WebPacker - Load NPM modules via ES6 Import vs webpack.ProvidePlugin()

I am experimenting with running multiple WebApps inside of Rails.

Each WebApp has totally different dependencies and I would like to keep the bundle sizes of each to minimum size.

The first app I am building uses Reveal.js and I have added it using yarn add reveal

I had thought I could include it by importing via packs/presentation.js

console.log('Presentation System');
import 'reveal';

Reveal.initialize({
  controls: true,
  progress: true,
  history: true,
  center: true,
  transition: 'none',
});

enter image description here

I then tried a slight variation import { Reveal } from 'reveal';

  console.log('Presentation System');
  import { Reveal } from 'reveal';

  Reveal.initialize({
    controls: true,
    progress: true,
    history: true,
    center: true,
    transition: 'none',
  });

enter image description here

I finally got Reveal.js to work by altering the WebPacker config in side rails

config/webpack/environment.js

I added in jQuery and Reveal.js as webpack plugins by using the following code

I am unsure whether this is the best way to include reveal as it seems like it would effect all my apps by adding jQuery and Reveal to each app which is not what I want as the other apps are using VUE or Angular

// https://joey.io/how-to-use-jquery-in-rails-5-2-using-webpack/
const { environment } = require('@rails/webpacker');
const typescript =  require('./loaders/typescript');
const vue =  require('./loaders/vue');

const webpack = require('webpack')

environment.loaders.append('vue', vue);
environment.loaders.append('typescript', typescript);

module.exports = environment;

environment.plugins.prepend(
    'Provide',
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      jquery: 'jquery',
      Reveal: 'reveal'
    })
);

And the code that I now run to display the presentation

$(document).ready(function() {

  Reveal.initialize({
    controls: true,
    progress: true,
    history: true,
    center: true,
    transition: 'none',
  });

});

Upvotes: 0

Views: 632

Answers (1)

Blitz
Blitz

Reputation: 500

What about import Reveal from 'reveal' ?

https://babeljs.io/docs/en/learn/#modules

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

By doing import { Reveal } from 'reveal' you are trying to import a Reveal named export of the Reveal module.

But Reveal is the default export.

Upvotes: 1

Related Questions