Is there a way to include file in coffee script?

后端 未结 6 1524
温柔的废话
温柔的废话 2020-12-16 10:10

I\'d like to know if there is a way to include a file in a coffee script. Something like #include in C or require in PHP...

6条回答
  •  孤街浪徒
    2020-12-16 11:04

    Tl;DR: Browserify, possibly with a build tool like Grunt...

    Solutions review

    Build tool + import pre-processor

    If what you want is a single JS file to be run in the browser, I recommend using a build tool like Grunt (or Gulp, or Cake, or Mimosa, or any other) to pre-process your Coffeescript, along with an include/require/import module that will concatenate included files into your compiled output, like one of these:

    • Browserify: probably the rising standard and my personal favourite, lets you to use Node's exports/require API in your code, then extracts and concatenates everything required into a browser includable file. Exists for Grunt, Gulp, Mimosa and probably most others . To this day I reckon it is probably the best solution if you're after compatibility both Node and the browser (and even otherwise)
    • Some Rails Sprocket-like solutions like grunt-sprockets-directives or gulp-include will also work in a consistent way with CSS pre-processors (though those generally have their own importing mechanisms)
    • Other solutions include grunt-includes or grunt-import

    Standalone import pre-processor

    If you'd rather avoid the extra-complexity of a build tool, you can use Browserify stand-alone, or alternatives not based on Node's require like coffeescript-concat or Coffee-Stir

    [Not recommended] Asynchronous dynamic loading (AJAX + eval)

    If you're writing exclusively for the browser and don't mind, or rather really want, your script being spread across several files fetched via AJAX, you can use a myriad of tools like:

    • yepnope.js or Modernizr's .load based on yepnope: Please note that yepnope is now deprecated by its maintainer, who recommend using build tools and concatenation instead of remote loading
    • RequireJS
    • HeadJS
    • jQuery's $.getScript
    • Vanilla AJAX + eval
    • your own implementation of AMD

提交回复
热议问题