In one of my projects, I'm going to exchange the js files step by step. One of my files (hta.js) contains this:
export function likeUnlikePost(element, $tag, $companyId) {
var elementId = element.target.getAttribute('data-id');
var action = $('#heart-button-' + elementId).attr('action');
if (action == null) {
action = $('#love-heart-button-' + elementId).attr('action');
}
$.post('/posts/ajax/edit/like/' + elementId, {
action: action,
tag: $tag,
companyId: $companyId,
})
.done(function (data) {
var response = data[elementId];
if (response == 'unliked') {
$('#heart-button-span-' + elementId)
.removeClass('htaRed').addClass('htaGrey');
$('#r-heart-button-span-' + elementId)
.removeClass('htaRed').addClass('htaGrey');
$('#r-heart-button-' + elementId).attr('action', 'like');
$('#heart-button-' + elementId).attr('action', 'like');
} else if (response == 'liked') {
$('#heart-button-span-' + elementId)
.removeClass('htaGrey').addClass('htaRed');
$('#r-heart-button-span-' + elementId)
.removeClass('htaGrey').addClass('htaRed');
$('#r-heart-button-' + elementId).attr('action', 'unlike');
$('#heart-button-' + elementId).attr('action', 'unlike');
}
$('#heart-likes-' + elementId)
.html(data['count']);
$('#r-heart-likes-' + elementId)
.html(data['count']);
$('#div-loved-posts')
.html(data['lovedPostsHtml'])
.foundation();
})
.fail(function (data) {
});
}
I would like to access this function on two sides in my project. I tried this in webpack.config.js :
var Encore = require('@symfony/webpack-encore');
Encore
.setOutputPath('web/assets/')
.setPublicPath('/assets')
.setManifestKeyPrefix('../assets')
.addEntry('hta', './app/Resources/js/hta.js')
.addEntry('app', './app/Resources/js/app.js')
.autoProvideVariables({
'hta': 'hta',
'global.hta':'hta',
})
.enableSassLoader()
.enableSourceMaps(!Encore.isProduction())
.cleanupOutputBeforeBuild()
.configureFilenames({
js: 'js/[name].js',
css: 'css/[name].css',
images: 'images/[name].[ext]',
// images: 'images/[path]/[name].[ext]',
fonts: 'fonts/[name].[ext]'
})
;
module.exports = Encore.getWebpackConfig();
But, when I try to access this function via
document.hta.likeUnlikePost($element, '');
I just get an error:
TypeError: document.hta is undefined
I thought I tried like in this example: enter link description here
But I can't get it to work correctly.
2 possibilities: 1/ use export like you do. So remove the file from webpack and call import {} from 'path to your file's. Here app/Resources/assets/hta.js 2/ use webpack remove export function and declare your function in a let now I think you can call directly your function
In two cases don't omit args.
Bye