首页 > 解决方案 > 未捕获的 ReferenceError:说未定义

问题描述

我尝试将我的从 hello.js 导入我function hello()的页面 sign_up.liquid。我浏览我的 main.js 以获得一个 bundle.js( browserify ./public/js/main.js -o ./public/js/bundle.js),但我有一个未捕获的 ReferenceError。为什么我不能使用我function hello()的 in sign_up.liquid ?

在此处输入图像描述

--hello.js

var hello = function(){
    console.log('I said Hello')
}

module.exports = hello;

--main.js

const say = require('./hello.js')

--bundle.js

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var hello = function(){
    console.log('I said Hello')
}

module.exports = hello;
},{}],2:[function(require,module,exports){
const say = require('./hello.js')

},{"./hello.js":1}]},{},[2]);

--sign_up.liquid

[...]
<script src="../js/bundle.js"></script>
<script>
    say.hello();
<script>

标签: javascriptnode.jsbundlebrowserifyliquid

解决方案


你的问题是因为你好是你的出口,所以你的进口 hello() 变成了说。

如果你只使用

say() 

你应该得到 hello() 函数的值。

或者,您可以使用解构方法为您的导出指定别名。

像这样的东西:

const { hello: say } = require('./hello.js');

此处有关解构的更多信息 具体而言,您可能需要查看名为:在页面的一半左右分配给新变量名称的部分。


推荐阅读