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.

3
  • The only difference I see between jquery and Rails-UJS is jquery is simply used, but @rails/ujs has a require("@rails/ujs").start() line in the top module. Commented Aug 2, 2019 at 19:26
  • Did you end up finding a way to resolve this, @RWDJ? Commented Aug 16, 2019 at 10:49
  • @s_dolan I did not. I ended up doing imports. Commented Sep 5, 2019 at 1:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.