I want something similiar to importing JSONs, but in case it's any file. For example, I want to be able to include plaintext or octet-stream without having the content parsed together with JavaScript source code.
I know that transpilers allow you to import assets (like import data from 'data.json'
), but they end up clustering the final bundle with content parsed as code. Thus I suggest an embed
expression, which would work everywhere (browser, Node etc.):
- Plain text (UTF-8)
let x = embed './thing.txt' as 'text/plain';
typeof x; // 'string'
- Binary
let y = embed './thing.bin' as 'application/octet-stream';
y.toString(); // '[object ArrayBuffer]'
- Plain text (omiting MIME type)
let z = embed './thing.txt';
typeof z; // 'string'
embed
would be a context keyword followed by a literal string. The other literal string is the MIME type. At least 'text/plain'
and 'application/octet-stream'
should be supported.
In other languages there is a similiar way of doing that:
- In Rust, the
std::include_str!
(UTF-8) andstd::include_bytes!
macros. - In ActionScript, the
[Embed]
metadata.
FAQ
But can't you just use fetch
, XHR (browser) or file system (Node) for this purpose? The idea is to be able to preload external resources regardless of environment (whether it's a browser or Node runtime). The idea is to also resolve resources from the relative path of a module (which is crucial for libraries).
But why if JavaScript does not have file system support? The idea is not to read file metadata or manipulate file, it's just to preload its contents.