Node.js 如何在Svelte中导入crypto?

Node.js 如何在Svelte中导入crypto?,node.js,svelte,rollup,rollupjs,Node.js,Svelte,Rollup,Rollupjs,我创建了一个基本的苗条项目(它使用汇总)。我想像这样将本机库crypto导入到项目中 // src/lib/encrypt.js import { randomBytes } from "crypto"; const encrypt = () => { return randomBytes(4); }; export { encrypt }; 然后像这样把它导入一个小文件 // src/App.svelte <script> import

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

// 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>
如何使crypto在我的场景中工作

注: 这可能与汇总的工作方式有关。经过一些研究,我发现
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
是一个要在服务器上运行的节点包,很难在浏览器中运行。rollup插件节点内置似乎是。自述文件中指出,加密包填充可能无法工作:

Crypto没有填充,我们只提供了browserify提供的commonjs,它可能无法工作,如果您真的需要,请将{Crypto:true}作为选项传递

您可能需要找到打算在浏览器中使用的替代软件包。根据您的使用情况,您还可以查看本机。

谢谢:)将查看web crypto api。
[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)