首页 > 解决方案 > 如何通过 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())

在此处输入图像描述

标签: javascriptnode.jsswiftnpmswiftui

解决方案


推荐阅读