Trinity76
Trinity76

Reputation: 665

how to require a javascript file in rails?

I use Rails 5.1 and have a javascript file in app/assets/javascripts vex.combined.js and how can I require it within application.js?

//= require jquery
//= require rails-ujs
//= require_tree .

var vex = require('vex.combined');

returns an error in browser console: ReferenceError: require is not defined

Update:

By using //= require vex.combined

How can I transform vex.registerPlugin(require('vex-dialog')); ?

It returns

ReferenceError: require is not defined

too.

Upvotes: 0

Views: 521

Answers (1)

fool-dev
fool-dev

Reputation: 7777

Look, you don't need to use this var vex = require('vex.combined');

Rails Asset Pipeline:

The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass, and ERB.

For example

When we include a file using application.js like //= require select2 then we access to this all methods like after requiring this then we just called the method like select2();

$("#ID").select2();

when we remove this //= require select2 from application.js then it will show

ReferenceError: select2 is not a function

Try the following.

For the most common usage of vex, you'll want to include vex, vex-dialog, the vex CSS file, and a theme file.

//= require vex.combined

make sure directory is ok, then try to run basic alert like

vex.dialog.alert('Thanks for checking out vex!')

that's actually ok.

var vex = require('vex-js')
vex.registerPlugin(require('vex-dialog'))

Above two lines code for browserify/webpack setup which you are trying.

Upvotes: 0

Related Questions