Stimulus Discourse

Class inheritance to set up an “Application Controller” without import

I know you can make use of JavaScript’s class inheritance to set up an “Application Controller” that will serve as the foundation for all of your controllers to build upon. How can you do this without calling import at the top of each file?

Before

import ApplicationController from "./application_controller";

export default class extends ApplicationController {
  sayHi () {
    super();
    console.log("Hello from a Custom controller");
  }
}

After

export default class extends ApplicationController {
  sayHi () {
    super();
    console.log("Hello from a Custom controller");
  }
}

I tried to do this with ProvidePlugin but I get the following error:

Uncaught TypeError: Super expression must either be null or a function
    at _inherits (controllers sync \.js$:56)

I was seeing the same error as you and I’ve managed to require ApplicationController everywhere using the following code. I’m using Rails, but I guess you could do this anywhere.

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
const { resolve } = require('path');

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    ApplicationController: [resolve('app/javascript/application_controller'), 'default'],
  })
)

module.exports = environment

Hope that helps.

1 Like

For posterity, this topic was resolved here: https://github.com/stimulusjs/stimulus/issues/313

1 Like