Skip to content

Instantly share code, notes, and snippets.

@revblaze
Last active December 21, 2020 23:31
Show Gist options
  • Save revblaze/f8cde4259e9e9324ef38673af839a52b to your computer and use it in GitHub Desktop.
Save revblaze/f8cde4259e9e9324ef38673af839a52b to your computer and use it in GitHub Desktop.
Read a JavaScript file and return its contents as a String (Swift)
struct JS {
static let index = "index" // index.js (default)
static let path = "dist/" // path/to/file.js
/// Returns the generated JavaScript code for `index.js` as a String.
static func get() -> String {
return get(file: index, path: path)
}
/// Returns the generated JavaScript code for a specified JavaScript `file`.
/// - parameters:
/// - file: The name of the JavaScript file you wish to retrieve (file extension is optional)
/// - returns: The contents of the input JavaScript file as a String
/// # Usage
/// let code = JS.get(file: "index")
/// webView.evaluateJavaScript(code)
static func get(file: String) -> String {
return get(file: file, path: path)
}
/// Returns the generated JavaScript code for a specified JavaScript `file`.
/// - parameters:
/// - file: The name of the JavaScript file you wish to retrieve (file extension is optional)
/// - path: The path to the directory where the JavaScript file is located
/// - returns: The contents of the input JavaScript file as a String
/// # Usage
/// let code = JS.get(file: "index", path: "dist/")
/// webView.evaluateJavaScript(code)
static func get(file: String, path: String) -> String {
if let filePath = Bundle.main.path(forResource: "\(path)\(file.removeExtension())", ofType: "js") {
do {
let contents = try String(contentsOfFile: filePath)
return contents
} catch {
print("Error: contents could not be loaded")
}
} else {
print("Error: \(file.removeExtension()).js not found")
}
return "Error"
}
}
extension String {
/// Removes the `.js` extension from the file name (ie. `"index.js" -> "index"`).
func removeExtension() -> String {
return self.replacingOccurrences(of: ".js", with: "")
}
}
@revblaze
Copy link
Author

revblaze commented Dec 21, 2020

Example Usage

JS.get()                  // dist/index.js as String
JS.get(file: "custom")    // dist/custom.js as String
JS.get(file: "func.js")   // dist/func.js as String

Importing the contents of a JavaScript file *.js and printing to console:

func printJS(fileName: String) {
  let js = JS.get(file: fileName)
  print(js)
}

Importing a JavaScript file *.js from resource sub-directory dist/ and executing upon webView didCommit:

class ViewController {
  func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    var js = JS.get()               // index.js (default)
    js = JS.get(file: "custom")     // custom.js
    webView.evaluateJavaScript(js)
  }
}

@revblaze
Copy link
Author

revblaze commented Dec 21, 2020

Optional Extension

Appends a dash to the path String if none exists:

extension String {
  /// Appends an ending dash to a path (ie. `"path" -> "path/"`).
  mutating func addPathDash() -> String {
    if !self.hasSuffix("/") {
      self.append("/")
    }
    return self
}

Example Usage

static func get(file: String, path: String) -> String {
  let fullPath = path.addPathDash() + file.removeExtension()
  if let filePath = Bundle.main.path(forResource: fullPath, ofType: "js") {
    do {
        ...
      }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment