3

I'm trying to use Rails from @rails/ujs in webpacker ts-loader similar to Rails in the asset pipeline. I want a global variable Rails available in all modules.

For now, I can circumvent the problem by importing it in each module, but, for the sake of addressing the problem, how can we make a global module that ts-loader won't cry about.

Firstly, I already have jquery configured as $. I don't see why @rails/ujs as Rails isn't working similarly. Here is my (simplified) configuration:

// tsconfig.json

{
  "compilerOptions": {
    ...
    "lib": ["dom", "es2020"],
    "module": "esnext",
    "moduleResolution": "node",
    "target": "es5"
  },
  "exclude": ["**/*.spec.ts", "node_modules", "vendor", "public"]
  ...
}
// config/webpack/loaders/typescript.js
...
module.exports = {
  rules: [
    {
      ...
      loader: 'ts-loader',
      options: { transpileOnly: true },
    },
    ...
  ],
  resolve: { plugins: ... },
}
// config/webpack/environment.js

...

// Globals
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  Rails: ['@rails/ujs'], /* also tried Rails: '@rails/ujs', */
}))
...

// app/.../packs/application/index.ts
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()

import './rails-inquirer'

// app/.../packs/application/rails-inquirer/index.ts
console.log(Rails)
$ bin/webpack --display errors-only
TS2304: Cannot find name 'Rails'

Related: This similar question is not a duplicate of my problem. That question does not address Typescript. Neither does its answer which I followed. It did, however, fix my eslint. I'm thinking this is a ts-loader config problem.

RWDJ
  • 734
  • 8
  • 13

0 Answers0