首页 > 解决方案 > 如何在 Svelte 中导入加密货币?

问题描述

我创建了一个基本的苗条项目(它使用汇总)。我想像这样将本机库、加密导入项目中。

// src/lib/encrypt.js

import { randomBytes } from "crypto";

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

export { encrypt };

并将其导入到一个像这样的苗条文件中,

// 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)
 

标签: node.jssvelterolluprollupjs

解决方案


crypto是一个打算在服务器上运行的 Node 包,在浏览器中运行很棘手。rollup-plugin-node-builtins 似乎已被弃用。它的继任者在自述文件中指出,填充加密包可能不起作用:

Crypto 没有填充,我们只提供来自 browserify 的 commonjs ,它可能不起作用,如果你真的想要它,请传递 {crypto: true} 作为选项。

您可能需要找到一个打算在浏览器中使用的替代包。根据您的用例,您还可以查看本机网络加密 API


推荐阅读