Search code examples
phplaravelcoffeescriptasset-pipelinelaravel-elixir

How to require other CoffeeScripts files in main CoffeeScript with Laravel?


I have one CoffeeScript project with "Ruby on Rails" framework. Now I want to use "Laravel" framework instead of "Ruby on Rails".

In "Ruby on Rails", there is "Sprocket" asset pipeline management library. With "Sprocket", I can import other coffeescript files in main coffeescript file with #= require or #= require_tree statement e.g.

#= require views/view
#= require_tree ./views

#= require_tree ./templates

init = ->
  document.removeEventListener 'DOMContentLoaded', init, false

  if document.body
    app.init()
  else
    setTimeout(init, 42)

What are the counterparts on Laravel for these #= require and #= require_tree statements? Is there any other ways to solve this problem with Elixir?


Solution

  • As there is no answer, I have to explore the solution by myself and here is the one.

    In Laravel-elixir version (2.3.6), there is a concatenation feature for coffeescript. You have to store coffeescript files in resources/assets/coffee directory. Then, the following script in gulpfile.js will generate a single app.js that compile and concatenate all coffeescripts in the provided array parameter.

    elixir(function(mix) {
       mix.coffee(['app.coffee', 'collection.coffee']);
    });
    

    So, you don't need to include other coffeescript files in main coffeescript file like in Sprocket of Ruby on Rails.

    But there is still one issue that how to require all coffeescript files in more than one directory. These coffeescript files should also be in order so that their dependencies don't broken. It is cumbersome to write each coffeescript file name in order to be required. The following script can perfectly solve this issue.

    mix.coffee([
        'lib/license.coffee',
        'lib/*.coffee',
    
        'app/app.coffee',
        'app/config.coffee',
        'app/*.coffee',
    
        'collections/collection.coffee',
        'collections/*.coffee',
    
        'models/model.coffee',
        'models/*.coffee',
    
        'views/view.coffee',
        'views/*.coffee',
    
        'templates/*.coffee',
    
        'application.coffee'
    ]);
    
    mix.scripts(null, 'public/js/vendor.js', 'resources/assets/coffee/vendor');
    

    You can require all coffeescript files in directory with *(asterisk) sign like that 'models/*.coffee'.

    You can also specify the file that should be required at first before requiring all the files in directory, by their filename like that 'models/model.coffee'. Laravel-elixir is intelligent enough to not compile and concatenate that file again.

    That's the way how I solved the problem in my question.