Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Compile SweetJS to String in Node.js

Compile SweetJS to String in Node.js

Problem

From the shell, I can call the Sweet.js compiler.

sjs -m macro-providing-module -o output-directory/file.js input-directory/file.sjs

How can I do the same from inside a Node.js module such that instead of outputting to a specified file, I get the compiled output as a string?

var sweetjs = require('sweet.js');
var input = require('fs').readSync('input-directory/file.sjs');
var module = 'macro-providing-module';

var output = sweetjs(/* ??? */);
Problem courtesy of: Havvy

Solution

Its undocumented because it will be changed/removed when sweet.js gets good module support (using ES6 imports instead of command line flags). But for 0.4.0 you can use the following API to load macros from npm modules:

var sweet = require('sweet.js');
var mod = sweet.loadNodeModule(root, modulePath);
var out = sweet.compile(, {
    modules: [mod]
});

The root argument is the location on the file system to start looking for node modules. Generally this is process.cwd() if you are making a command line tool or something. compile takes an options object where you can provide an array of modules.

If you just want to compile a string as a module, you can use sweet.loadModule().

Again, this API is merely a stop-gap and will be removed in the near future.

Edit: corrected the compile API

Solution courtesy of: Nathan Faubion

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Compile SweetJS to String in Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×