首页 > 解决方案 > npm webpack-mix - 从文件中调用 javascript 函数

问题描述

我正在尝试访问table.js文件中定义的函数index.html
表.js

    let table;

    function set_table(table) {
      this.table = table;
      console.log("function called successfully");
    }
    
    export {set_table}; 


索引.html

    <script src="table.js"></script>

    <script type="text/javascript">

      set_table("test");

    </script>

我正在使用 npm webpack mix 来编译table.js并接收错误Uncaught ReferenceError: set_table is not defined

请建议访问table.js功能的最佳方式index.html

标签: javascripthtmljquerynpmwebpack

解决方案


模块导出需要设置为window. 因此,只需导入set_table脚本 type="module" 然后将其设置windowwindow.set_table

    <script type="module">
          import { set_table } from "./table.js";
          window.set_table = set_table;
        </script>

看到这个答案https://stackoverflow.com/a/69083651/1109657


推荐阅读