Skip to content

Commit

Permalink
Have Unity auto import .cjs files as TextAssets. These files are reco…
Browse files Browse the repository at this point in the history
…gnized by IDEs as JavaScript files (for syntax highlighting and debugging), and can be used directly with NodeJS.
  • Loading branch information
yuatpocketgems committed Dec 13, 2020
1 parent 98f7c7a commit ff24112
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
14 changes: 14 additions & 0 deletions unity/Assets/Puerts/Src/Editor/CJSImporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.IO;
using UnityEditor.Experimental.AssetImporters;
using UnityEngine;

[ScriptedImporter(1, "cjs")]
public class CJSImporter : ScriptedImporter
{
public override void OnImportAsset(AssetImportContext ctx)
{
TextAsset subAsset = new TextAsset( File.ReadAllText( ctx.assetPath ) );
ctx.AddObjectToAsset("text", subAsset);
ctx.SetMainObject( subAsset );
}
}
15 changes: 12 additions & 3 deletions unity/Assets/Puerts/Src/Loader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,20 @@ public DefaultLoader(string root)
this.root = root;
}

private string pathToUse(string filepath)
{
return filepath.EndsWith(".cjs") ?
filepath.Substring(0, filepath.Length - 4) :
filepath;
}

public bool FileExists(string filepath)
{
#if PUERTS_GENERAL
return File.Exists(Path.Combine(root, filepath));
#else
return UnityEngine.Resources.Load(filepath) != null;
string pathToUse = this.pathToUse(filepath);
return UnityEngine.Resources.Load(pathToUse) != null;
#endif
}

Expand All @@ -45,7 +53,8 @@ public string ReadFile(string filepath, out string debugpath)
debugpath = Path.Combine(root, filepath);
return File.ReadAllText(debugpath);
#else
UnityEngine.TextAsset file = (UnityEngine.TextAsset)UnityEngine.Resources.Load(filepath);
string pathToUse = this.pathToUse(filepath);
UnityEngine.TextAsset file = (UnityEngine.TextAsset)UnityEngine.Resources.Load(pathToUse);
debugpath = System.IO.Path.Combine(root, filepath);
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
debugpath = debugpath.Replace("/", "\\");
Expand All @@ -54,4 +63,4 @@ public string ReadFile(string filepath, out string debugpath)
#endif
}
}
}
}
1 change: 1 addition & 0 deletions unity/Assets/Puerts/Src/Resources/puerts/cjsload.js.txt
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ var global = global || (function () { return this; }());
return searchModuleInDirWithExt(dir, requiredModule);
} else {
return searchModuleInDirWithExt(dir, requiredModule + ".js")
|| searchModuleInDirWithExt(dir, requiredModule + ".cjs")
|| searchModuleInDirWithExt(dir, requiredModule + "/index.js")
|| searchModuleInDirWithExt(dir, requiredModule + "/package.json");
}
Expand Down

0 comments on commit ff24112

Please sign in to comment.