首页 > 解决方案 > 这个 npm 包可以导入吗?

问题描述

您好我正在尝试将一个名为“jquery.terminal”的 npm 包导入我的项目中。

我正在通过命令行使用 browserify 来转换 require("jquery.terminal"); 解释器将语句转换成可读的代码。

这是我当前的代码。

require("jquery.terminal");

jQuery(function($, undefined) {
    $('#term_demo').terminal(function(command) {
        if (command !== '') {
            try {
                var result = window.eval(command);
                if (result !== undefined) {
                    this.echo(new String(result));
                }
            } catch(e) {
                this.error(new String(e));
            }
        } else {
           this.echo('');
        }
    }, {
        greetings: 'JavaScript Interpreter',
        name: 'js_demo',
        height: 200,
        prompt: 'js> '
    });
});

这是 npm 上的包https://github.com/jcubic/jquery.terminal

这是我的错误

jQuery.Deferred exception: $(...).terminal is not a function TypeError: $(...).terminal is not a function
    at HTMLDocument.<anonymous> (file:///C:/Dev/term-game/bundle.js:6:21)
    at mightThrow (file:///C:/Dev/term-game/bundle.js:11049:29)
    at process (file:///C:/Dev/term-game/bundle.js:11117:12) undefined
jQuery.Deferred.exceptionHook @ bundle.js:11333
process @ bundle.js:11121
setTimeout (async)
(anonymous) @ bundle.js:11155
fire @ bundle.js:10783
fireWith @ bundle.js:10913
fire @ bundle.js:10921
fire @ bundle.js:10783
fireWith @ bundle.js:10913
ready @ bundle.js:11393
completed @ bundle.js:11403
bundle.js:6 Uncaught TypeError: $(...).terminal is not a function
    at HTMLDocument.<anonymous> (bundle.js:6)
    at mightThrow (bundle.js:11049)
    at process (bundle.js:11117)

标签: jquerynpmecmascript-6browserifyjquery-terminal

解决方案


您需要包含 jQuery,因此您有 jQuery 对象,然后 jQuery Terminal 也 UMD jQuery Terminal 使用 require 调用函数并将所有依赖项传递给它,在这种情况下只是 jQuery。

var $ = require('jquery');
require('jquery.terminal')($);

$('#term').terminal();

推荐阅读