[英]Why doesn't this JS function properly import to my blade.php?
I have a JavaScript file, 'submittedForms.js' that I reference in my blade.php
with我有一个 JavaScript 文件“submittedForms.js”,我在我的blade.php
引用了blade.php
<script type="module" src="/js/bundle/charts/submittedForms.js"></script>
In submittedForms.js
, I've defined a simple function called ' functionTest ' and a variable that represents a chart called ' submittedForms '.在submittedForms.js
,我定义了一个名为“ functionTest ”的简单函数和一个代表名为“ submittedForms ”的图表的变量。 I want to import both in my blade.php.我想在我的blade.php 中导入两者。 The chart variable imports and is rendered fine!图表变量导入并呈现良好! However, when I add the function and alter the export to be;但是,当我添加函数并将导出更改为时;
module.exports = {
functionTest() {
console.log('this works');
},
submittedForms
};
the following error thrown from the blade pops up;弹出刀片抛出的以下错误;
"Uncaught ReferenceError: functionTest is not defined" “未捕获的 ReferenceError:未定义 functionTest”
In the blade.php
I'm calling functionTest like this;在blade.php
我像这样调用functionTest;
functionTest()
The issue here is because you're using module.export
which is used for importing/requiring
files between js file (this can be expanded on greatly but for the sake of the question I will keep it simple).这里的问题是因为您使用的是module.export
,它用于在 js 文件之间importing/requiring
文件(这可以大大扩展,但为了这个问题,我会保持简单)。
I would imagine that you're currently getting a warning in your console along the lines of:我想您目前在控制台中收到以下警告:
Uncaught ReferenceError: module is not defined (Unless you have an )未捕获的 ReferenceError:未定义模块(除非您有 )
To have you functionTest
be available in your browser you can either define it as:为了让您的functionTest
在您的浏览器中可用,您可以将其定义为:
function functionTest() {
console.log('this works');
}
which will attach it to the parent scope which in this case will be the window
.它将它附加到父作用域,在这种情况下将是window
。 Or you can explicitly attach it to the window
object by:或者您可以通过以下方式将其显式附加到window
对象:
or或者
window.functionTest = function () {
console.log('this works');
}
If you're wanting to use the newer ES modules for importing/exporting this would be possible, however, support won't be that great at the time of writing.如果您想使用较新的 ES 模块进行导入/导出,这是可能的,但是,在撰写本文时支持不会那么好。 To achieve this you should change module.exports
to export default
:为此,您应该将module.exports
更改为export default
:
export default {
functionTest() {
console.log('this works');
},
submittedForms
};
Then in your blade file you could import it inside a script tag with the attribute type="module"
:然后在您的刀片文件中,您可以将其导入到属性type="module"
的脚本标签中:
<script type="module"> //notice the
import submittedForms from "/js/bundle/charts/submittedForms.js";
submittedForms.functionTest();
</script>
Right way to import JS file should look like this.导入 JS 文件的正确方法应该是这样的。 Hopefully this will work.希望这会奏效。
<script src="{{ asset('js/bundle/charts/submittedForms.js')}}"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.