1

from command line, how to pass a variable to coffeescript, so it can replace a corresponding placeholder, something like this:

$ echo "module.exports = {version: '$VERSION'}" | coffee -p -s VERSION=0.0.0

Expected JS:

(function() {

  module.exports = {
    version: '0.0.0'
  };

}).call(this);

Thank you

1
  • 1
    CoffeeScript alone won't do this for you. This question has some discussion of preprocessors that could run either before or after coffee. Commented May 3, 2012 at 12:41

1 Answer 1

3

Two things:

  • You need to define VERSION in the echo, not in the coffeescript compiler; by the time the coffeescript compiler sees it it's already translated $VERSION into ''.
  • echo is a shell builtin, and therefore the standard VERSION=0.0.0 echo "$VERSION" construct doesn't work.

So you want to create a new subshell so that the setting of VERSION doesn't propagate into your main shell, then perform the echo and coffee, like so:

$ (VERSION=0.0.0; echo "module.exports = {version: '$VERSION'}" | coffee -ps)       
(function() {

  module.exports = {
    version: '0.0.0'
  };

}).call(this);

The parentheses around the expression stop VERSION from being set:

$ echo $VERSION                                                              

$
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, my example is probably too simple... Your trick works well but it's rather a shell rather a coffee one. What if I want to compile a whole folder: coffee -c -o lib/ src/ but with VERSION=0.0.0 so $VERSION placeholder is replaced somewhere in src/? Thanks

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.