Stimulus Discourse

Struggling using stimulus with rollup.js (via gulp)

#1

Hi there.

Hoping someone can assist me here :wink: I’m pretty new to using module bundlers in client side js code.
I asked on github about using the IE polyfils for stimulus, without needed to go all-in with webpack - the responses were helpful - and rollup.js looked like a nice solution to allow me to use stimulus properly in my web app, without having to totally switch to webpack.

I can get things working with rollupjs - here’s my “entry point” for example:

import { Application } from "stimulus"

import HelloController from "../controllers/hello_controller"

StimulusDelegates();
const application = Application.start();
application.register("hello", HelloController);

I’ve got a gulp task to deal with this, that calls rollup:

const rollupJS = (inputFile, options) => {
    return () => {
        return rollup({
            input: options.basePath + inputFile,
            format: options.format,
            sourcemap: options.sourcemap,
            plugins: [rollupResolve()]
        })
        // point to the entry file.
            .pipe(source(inputFile, options.basePath))
            // we need to buffer the output, since many gulp plugins don't support streams.
            .pipe(buffer())
            .pipe(sourcemaps.init({loadMaps: true}))
            .pipe(babel({
                presets: [['@babel/preset-env', {modules: false}]],
                plugins: ['@babel/plugin-proposal-class-properties']
            }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest(options.distPath));
    };
}

All that seems to be working, and gives me a nice file that seems to work on most browsers, apart from IE11 :frowning:

So - I npm install the @stimulus/polyfills, and add this to the start of my entry point JS file:

import "@stimulus/polyfills"

But when I rollup that file now, and try to run it, I get an error:

Uncaught ReferenceError: require is not defined
    at find.js:1
    at UserListingStimulus.js? [sm]:1

And sure enough, when I look at the JS rollup has generated, it’s peppered with “require” statements - which obviously aint gonna work :frowning: - here’s a snippet of the generated code:

require('../../modules/es6.array.find');

  module.exports = require('../../modules/_core').Array.find;

  require('../../modules/es6.array.find-index');

Does anyone know what’s going on here, or what I can do to sort it out?! Things were looking so good with rollup 'till now !

#2

I think you need to add the https://github.com/rollup/rollup-plugin-commonjs plugin.

See https://github.com/rollup/rollup-plugin-node-resolve#using-with-rollup-plugin-commonjs and https://gist.github.com/javan/b05031b4f77851dd80a6e69495f5888a for examples.