简体   繁体   English

如何在浏览器中导入require模块 javascript

[英]How to import require module in browser javascript

I want to make a jupyter notebook extension and I am following this repo .我想做一个 jupyter notebook 扩展,我正在关注这个 repo I needed to run python code using javascript for which I am trying to use the npm python-shell我需要使用 javascript 运行 python 代码,为此我尝试使用npm python-shell

To import the package, I tried using require module but its not working because it is not supposed to be run on browser and requires nodejs .要导入 package,我尝试使用require模块但它不起作用,因为它不应该在浏览器上运行并且需要nodejs I tried searching for other ways to run nodejs on browser and found stuff like browserify etc. However, the file main.js in the repo linked above is using the require module comfortably.我尝试寻找在浏览器上运行 nodejs 的其他方法,并找到了类似 browserify 等的东西。但是,上面链接的 repo 中的文件main.js正在舒适地使用require模块。 How is it doing so?它是怎么做到的? What am I missing?我错过了什么? Below is the code and the error I get in the browser.下面是我在浏览器中得到的代码和错误。 I have installed require and python-shell module using npm already.我已经使用 npm 安装了requirepython-shell模块。

Code:代码:

define(['require','PythonShell','base/js/namespace', 'base/js/events'], function (require,Jupyter, events) {
  

  var PythonShell = require('python-shell');
  PythonShell.runString('x=1;print(x)',null,function(err,results) {
    console.log(results);
  });

  function load_ipython_extension() {
    console.log("Hello World");
  }
  return {
    load_ipython_extension: load_ipython_extension,
  };
});

Error:错误:

It looks like the library you are trying to use, python shell was designed for node.js, as stated in their package description:看起来您正在尝试使用的库python shell是为 node.js 设计的,如其 package 描述中所述:

A simple way to run Python scripts from Node.js with basic but efficient inter-process communication and better error handling.一种从 Node.js 运行 Python 脚本的简单方法,具有基本但高效的进程间通信和更好的错误处理。

Because of that, you cannot use this package in the browser.因此,您无法在浏览器中使用此 package。 There are probably lots of alternatives, and I found this package through some quick googling: pyodide (note, I have never used this myself, I just found it).可能有很多替代品,我通过一些快速谷歌搜索找到了这个 package: pyodide (注意,我自己从未使用过它,我只是找到了它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM