Skip to content

Instantly share code, notes, and snippets.

@sundbry
Forked from austinbirch/cljs-metro-transformer.js
Last active February 1, 2019 06:12
Show Gist options
  • Save sundbry/55bb902b66a39c0ff83629d9a8015ca4 to your computer and use it in GitHub Desktop.
Save sundbry/55bb902b66a39c0ff83629d9a8015ca4 to your computer and use it in GitHub Desktop.
Transform compiled Clojurescript code for React Native/Metro (Updated for RN 0.58)
/**
* Copyright (c) 2015-present, Facebook, Inc.
* Copyright (c) 2018 Arctype Corp.
*
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of the facebook/react source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Note: This is a fork of the fb-specific transform.js
*/
'use strict';
var JsTransformer = require("./node_modules/metro/src/JSTransformer/worker");
var fs = require("fs");
function transformCode(buf, deps) {
var out = "__d(function (global, _$$_REQUIRE, _$$_IMPORT_DEFAULT, _$$_IMPORT_ALL, module, exports, _dependencyMap) {\n" +
"var __dependencyIndex = {}\n";
for (var i = 0; i < deps.length; i++) {
out += "__dependencyIndex[\"" + deps[i].name + "\"] = _dependencyMap[" + i.toString() + "];\n";
}
out += "var __lookupRequire = function(name) { if(__dependencyIndex[name]) { return __dependencyIndex[name]; } else { throw new Error('Module is not defined: ' + name); }};\n" +
"var require = function(name) { return _$$_REQUIRE(__lookupRequire(name), name); };\n";
out += buf.toString("utf8") +
"\n});";
return out;
}
async function transformAsync(jsTransformer, filename, codebuf, options) {
if (!options.hot && filename.startsWith("index.") && filename.endsWith(".js")) {
console.log("Invoking custom TRANSFORM:" + filename);
var mockBuffer = fs.readFileSync("cljs-deps.js");
var mock = await jsTransformer.transform(filename, mockBuffer, options);
return {
dependencies: mock.dependencies,
output: [{data: {code: transformCode(codebuf, mock.dependencies), map: []},
type: 'js/module'}],
getSource: function() { return codebuf }
}
}
else {
return await jsTransformer.transform(filename, codebuf, options);
}
}
class ClosureTransformer {
constructor(projectRoot, config) {
this._projectRoot = projectRoot;
this._config = config;
this._jsTransformer = new JsTransformer(projectRoot, config);
}
transform(filename, codebuf, options) {
return transformAsync(this._jsTransformer, filename, codebuf, options);
}
};
module.exports = ClosureTransformer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment