Symfony 4:Webpack Encore-其他JS文件中的调用方法

bar*_*892 2 symfony webpack

我想在index.js文件中调用的方法app.js。但是我得到了错误app.test is not a function。我的摘录webpack.config.js

Encore
    .addEntry('app', './assets/js/app.js')
    .addEntry('index', './assets/js/index.js')
    .setOutputPath('public/build/')
    .createSharedEntry('vendor', [
       './assets/js/vendor/jquery-3.2.1.slim.min.js'
    ])
   .autoProvideVariables({
       $: 'jquery',
       jQuery: 'jquery',
       'window.jQuery': 'jquery'
   });
Run Code Online (Sandbox Code Playgroud)

app.js仅包含test方法:

function test() {
    return "test123";
}
Run Code Online (Sandbox Code Playgroud)

index.js尝试调用此方法:

let app = require("./app");

$(document).ready(function () {
    console.log(app); // empty object {}
    console.log(app.test());
});
Run Code Online (Sandbox Code Playgroud)

此设置有什么问题?我是否误解了webpack的概念?我认为可以像上面的示例一样,需要所需的模块并访问它们。

Iwa*_*aya 5

首先,您的模块是相关的,因此您只应使用1个js条目。从中删除您的app.js条目webpack.config.js。接下来在您的app.js中,导出您的函数

function test() {
    return "test123";
}

module.exports = {
    test
};
Run Code Online (Sandbox Code Playgroud)

在你的index.js中

let app = require("./app");

$(document).ready(function () {
    app.test()
});
Run Code Online (Sandbox Code Playgroud)

或使用ESM模块的替代方法:

app.js

export function test() {
    return "test123";
}
Run Code Online (Sandbox Code Playgroud)

index.js

import { test } from './app';

$(document).ready(function () {
    test();
});
Run Code Online (Sandbox Code Playgroud)