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

时间:2018-05-20 07:16:20

标签: 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'
   });

app.js仅包含test方法:

function test() {
    return "test123";
}

index.js尝试调用此方法:

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

$(document).ready(function () {
    console.log(app); // empty object {}
    console.log(app.test());
});

此设置有什么问题?我误解了webpack的概念吗?我认为有可能需要所需的模块并像上面的例子那样访问它们。

1 个答案:

答案 0 :(得分:3)

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

function test() {
    return "test123";
}

module.exports = {
    test
};

在index.js

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

$(document).ready(function () {
    app.test()
});

使用ESM模块的替代方法:

app.js

export function test() {
    return "test123";
}

index.js

import { test } from './app';

$(document).ready(function () {
    test();
});