diff --git a/bin/build.js b/bin/build.js
index <HASH>..<HASH> 100644
--- a/bin/build.js
+++ b/bin/build.js
@@ -181,17 +181,20 @@ var build = function (args, callback) {
     }
     fs.writeFileSync(configPath, JSON.stringify(config));
 
-
-    global.libxml = require("libxml");
-
-    // start optimizing
-    requirejs.optimize(optimizeConfig, function (results) {
+    var writeBackConfig = function(){
         // write back normal config
         delete config['optimizedXAML'];
         config.baseUrl = realBaseUrl;
 
         fs.writeFileSync(configPath, JSON.stringify(config));
+    };
+
+    global.libxml = require("libxml");
 
+    // start optimizing
+    requirejs.optimize(optimizeConfig, function (results) {
+        // write back normal config
+        writeBackConfig();
 
         var indexFilePath = path.join(buildDirPath, buildConfig.indexFile || "index.html");
         var indexFile = fs.readFileSync(indexFilePath, "utf8");
@@ -207,10 +210,13 @@ var build = function (args, callback) {
         }
         fs.writeFileSync(indexFilePath, content);
     }, function(err){
+        writeBackConfig();
+
         console.log(err);
     });
 };
 
+
 build.usage = "rappidjs build";
 
 module.exports = build;
fixed writing back config when error happens