javascript - Uncaught ReferenceError : say is not defined

标签 javascript node.js bundle browserify liquid

我尝试将我的函数hello()从hello.js导入到我的页面sign_up.liquid。 我浏览器化我的 main.js 以获得一个bundle.js(browserify ./public/js/main.js -o ./public/js/bundle.js),但我有一个 Uncaught ReferenceError 。为什么我无法在 sign_up.liquid 中使用我的函数 hello()

enter image description here

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

最佳答案

你的问题是因为 Hello 是你的导出,所以你的 import hello() 变成了 say。

如果您只使用

say() 

您应该获得 hello() 函数的值。

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

类似这样的事情:

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

有关 Destructuring here 的更多信息 具体来说,您可能需要查看位于页面中间位置的名为:分配给新变量名称的部分。

关于javascript - Uncaught ReferenceError : say is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59406464/

相关文章:

javascript - python Flask 动态下拉列表

node.js - 如何将 async/await 与 mongoose 聚合一起使用

javascript - 将 node.js 服务器端代码移植到 HTML5 WebSockets

ios - XCAssets 未复制到应用程序包

java - Glassfish 3.1.2.2 和重用 Bundle ID

javascript - 在JavaScript中计算跳跃动画

javascript - 单击提交按钮后,如何将行数据提交到 laravel 5.2 中的 Controller ?

asp.net - 在不支持 javascript 的浏览器中使用 ASP.NET

javascript - 如何在不闪烁的情况下一次隐藏单个 div 而不是设置可见性隐藏

iphone - 如何创建 bundle