Symfony 4 + Webpack Encore:如何在index.js中调用app.js的方法?
问题分析与解决方案
嘿,这个问题的核心是你没搞懂webpack依赖的模块导出/导入机制,咱们拆解来看:
为什么会出现app.test is not a function?
在webpack(以及CommonJS/ES模块规范)里,每个JS文件都是一个独立的模块,模块内部的变量、函数默认是私有的,不会自动对外暴露。你的app.js里的test函数只是定义了一个局部函数,没有做任何导出操作,所以当index.js通过require("./app")引入它时,默认拿到的就是一个空对象{},自然就找不到test方法了。
怎么解决?
只需要在app.js里显式导出test函数,让其他模块能访问到它,有两种常用方式:
方式1:使用CommonJS规范导出(和你当前的require写法匹配)
修改app.js:
function test() { return "test123"; } // 把test函数挂载到module.exports上,暴露给外部 module.exports = { test };
或者如果只需要导出这一个函数,也可以直接导出函数本身:
function test() { return "test123"; } module.exports = test;
对应的index.js就要改成这样调用:
let test = require("./app"); $(document).ready(function () { console.log(test()); // 输出test123 });
方式2:使用ES模块规范导出(更现代的写法)
如果你的webpack配置支持ES模块(现在大部分默认支持),可以用export语法:
修改app.js:
export function test() { return "test123"; }
或者用默认导出:
export default function test() { return "test123"; }
对应的index.js用import引入:
// 对应命名导出 import { test } from "./app"; // 对应默认导出 // import test from "./app"; $(document).ready(function () { console.log(test()); });
关于你的webpack配置
顺便说一句,你当前的webpack entry配置本身没有问题——把app和index都作为入口是允许的,而且你在index.js里通过require引入app.js的方式是正确的,webpack会自动处理这个模块依赖,不需要额外配置。
内容的提问来源于stack exchange,提问作者baris1892
相关产品推荐
相关产品推荐

