最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Importing a JavaScript function into HTML? - Stack Overflow

programmeradmin4浏览0评论

I have a JavaScript file called 'test.js' and in that file is this code snippet;

function functionTest() {
    console.log('this works');
}

I then import test.js into the head of my HTML inside a blade.php with;

<script type="module" src="/js/test.js"></script>

Finally, in the script tag in the body portion of my HTML, I call functionTest with

<script>
    functionTest()
</script>

However I never get a console.log. Instead, this error is thrown from my HTML;

Uncaught ReferenceError: functionTest is not defined<

I have a JavaScript file called 'test.js' and in that file is this code snippet;

function functionTest() {
    console.log('this works');
}

I then import test.js into the head of my HTML inside a blade.php with;

<script type="module" src="/js/test.js"></script>

Finally, in the script tag in the body portion of my HTML, I call functionTest with

<script>
    functionTest()
</script>

However I never get a console.log. Instead, this error is thrown from my HTML;

Uncaught ReferenceError: functionTest is not defined<

Share Improve this question asked Jan 9, 2020 at 20:06 ThirdGhostHandThirdGhostHand 3976 silver badges19 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

Your <script> tag is importing the JS file as a module.

As such it must be treated as a module, e.g., you need to export something, and import it to use it in your main file.

If you just want to use it as-is, without module-ish work, remove the type="module" from the <script> tag.

Export your function:

const functionTest = () => {
    console.log('this works')
};

export default functionTest;

Then you can import it as module.

发布评论

评论列表(0)

  1. 暂无评论