Skip to content

Smart Import

Shane Brinkman-Davis Delamore edited this page Mar 29, 2018 · 2 revisions

Related: Modules and CommonJs

CaffeineScript has a different version of import. It automatically imports any unassigned variable references from the specified library-objects, and, failing that, from the global namespace:

Example

import allows you to do this (*):

# CaffeineScript
import
  &ArtFoundation
  &ArtAtomic
  &ArtReact

Instead of this:

# NOTE: this is how I'd hand-code the same code in CoffeeScript,
# but it's not exactly the same semantics as the code generated by
# CaffeineScript. See the second example below for an exact comparison.

# CoffeeScript
Foundation = require "art-foundation"
Atomic = require "art-atomic"
React = require "art-react"

{log, capitalize} = Foundation
{point, hslColor} = Atomic
{
  createComponentFactory
  Component
  CanvasElement
  Element
  RectangleElement
  TextElement
  arrayWithout
} = React

(*) see CommonJs for more about the &Foo syntax

Motivation

Manual library extraction has several problems:

  • Busy work: It's verbose, and it's something the compiler can do for us.
  • Error prone: I constantly have to fix errors due to not including the right things.
  • Garbage: An imported value that is not used causes no errors, but it has a runtime cost as well as cluttering up source files. I regularly find my own files have more than 50% garbage in their imports - and I'm not a lazy coder.

Another, Simpler Example

This example shows exactly equivalent code in CaffeineScript, CoffeeScript and Javascript.

# CaffeineScript
import Foundation
merge b, c
# CoffeeScript
{merge = global.merge} = Foundation
merge b, c
// JavaScript ES6 (EcmaScript6)
let {merge = global.merge} = Foundation;
merge(a, b);
// JavaScript version ES5 (EcmaScript5)
let merge = Foundation.merge || global.merge;
merge(a, b);

Vs Javascript 'with'

import looks a bit like the maligned Javascript 'with', but there are significant differences: Comparing Import and With

Clone this wiki locally