如何在 Svelte 中导入加密货币?

How do I import crypto in Svelte?

我创建了一个基本的 svelte 项目(它使用汇总)。我想像这样导入一个本地库,加密到项目中。

// src/lib/encrypt.js

import { randomBytes } from "crypto";

const encrypt = () => {
  return randomBytes(4);
};

export { encrypt };

然后像这样将其导入到一个 svelte 文件中,

// src/App.svelte
<script>
    import {encrypt} from './lib/encrypt';
</script>

<main>
    <p>{encrypt()}</p>
</main>

这样做,产量,

Uncaught TypeError: crypto.randomBytes is not a function
    at encrypt (encrypt.js:4)
    at Object.create [as c] (App.svelte:9)
    at init (index.mjs:1496)
    at new App (App.svelte:3)
    at main.js:3

如何为我的方案启用加密?

注意: 这可能与汇总的工作方式有关。经过一些研究,我发现 rollup-plugin-node-builtins 用于加载本机模块。这似乎也不起作用。我尝试配置 rollup.config.js

// rollup.config.js
import svelte from "rollup-plugin-svelte";
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
import css from "rollup-plugin-css-only";
import preprocess from "svelte-preprocess";
import builtins from "rollup-plugin-node-builtins";

const production = !process.env.ROLLUP_WATCH;

function serve() {
  let server;

  function toExit() {
    if (server) server.kill(0);
  }

  return {
    writeBundle() {
      if (server) return;
      server = require("child_process").spawn(
        "npm",
        ["run", "start", "--", "--dev"],
        {
          stdio: ["ignore", "inherit", "inherit"],
          shell: true,
        }
      );

      process.on("SIGTERM", toExit);
      process.on("exit", toExit);
    },
  };
}

export default {
  input: "src/main.js",
  output: {
    sourcemap: true,
    format: "iife",
    name: "app",
    file: "public/build/bundle.js",
  },

  plugins: [
    svelte({
      preprocess: preprocess(),
      compilerOptions: {
        // enable run-time checks when not in production
        dev: !production,
      },
    }),
    css({ output: "bundle.css" }),
    resolve({
      browser: true,
      dedupe: ["svelte"],
    }),
    builtins({ crypto: true }),
    commonjs(),
    !production && serve(),
    !production && livereload("public"),
    production && terser(),
  ],
  watch: {
    clearScreen: false,
  },
};

这会产生,

[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)
 

crypto 是一个 Node 包,旨在 运行 在服务器上,并且很难 运行 在浏览器中。 rollup-plugin-node-builtins 似乎是 deprecated. Its successor 自述文件中的状态,填充加密包可能不起作用:

Crypto is not shimmed and and we just provide the commonjs one from browserify and it will likely not work, if you really want it please pass {crypto: true} as an option.

您可能需要找到一个旨在在浏览器中使用的替代包。根据您的用例,您还可以查看本机 web crypto API.

您可能喜欢加密包装

https://www.npmjs.com/package/crypto-wraps

只需对您的应用程序代码进行少量更改,您就可以 运行 在浏览器中或 node.js 有一个用于节点的 lib/。并且,浏览器的客户端/。

这只会使处理加密货币变得比直接处理更容易一些。我将在几天内添加椭圆派生密钥。而且,我正在考虑什么样的精巧组件可能适合专注于加密。