javascript - 如何通过 Content View 运行从 iPhone 上的 npm-library 导入的 JS 脚本?
问题描述
我在 x 代码项目的共享文件夹中有此代码和 node_modules。它必须向我显示从 js 代码生成的文本密钥。js-code 在 node.js 外部工作,但它在内容视图中显示“未定义”。我可以在 x 代码项目中导入 js 模块吗?它可以在 iPhone 上运行吗?
// ContentView.swift
// Shared
import Foundation
import SwiftUI
import JavaScriptCore
class Cube {
func doJS(text: String) -> String? {
let jsSource = "var testFunct = function test(message) { const NodeRSA = require('node-rsa'); const key = new NodeRSA(); var k = key.generateKeyPair(); var p = k.exportKey('pkcs1'); return p};"
let context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
return testFunction?.call(withArguments: [text]).toString()
}
}
struct ContentView: View {
var body: some View {
Text(Cube().doJS(text: "Hello, world!") ?? "No result")
.fontWeight(.black)
.foregroundColor(Color.green)
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我的js代码:
// npm install node-rsa
// https://www.npmjs.com/package/node-rsa
var testFunct = function test(message) {
const NodeRSA = require('node-rsa');
const key = new NodeRSA();
var k = key.generateKeyPair();
var p = k.exportKey('pkcs1');
return p};
console.log(testFunct())
解决方案
推荐阅读
- php - Laravel 应用程序需要超过 2s 来启动任何页面
- javascript - 如何通过 react-share 共享动态生成的图像?
- go - cgo 在 cgo 标头中写了 func 来打印数据,但没有打印任何内容
- haskell - Haskell - 在显示 2 次幂的函数中过滤赔率
- c# - 使用延续任务的链式任务
- spring - 如何使用firebase令牌ID在spring boot中实现身份验证?
- javascript - webpack中动态导出js文件
- python - Django 博客应用程序不会显示编辑帖子页面
- python - 如何读取 csv 文件并将逗号从数字转换为点?
- android - 带有 Flutter 的 AppCenter(IOS 和 Android)