First of all: I know there are several topics in this forum already touching issues like that, but I have read them all and they do not provide a solution.
My problem is the following:
I’m trying to localize my scripts to pass a nonce to the main javascript file. However it does not seam to work in Sage 9. Here is my code:
You’ve only posted a small snippet of your code, but based on some experimentation with a clean Sage install, my guess is that you’re not putting these function calls inside of an appropriate action. In app/setup.php, the original call to wp_enqueue_script() is wrapped in an add_action() call to wp_enqueue_scripts. When the code you posted is put inside that call, it appears to work correctly:
Just running wp_enqueue_script/style on its own has no effect: It needs to be hooked to an action so it’s run at the appropriate time. wp_enqueue_scripts is generally a good hook to grab onto for that purpose.
Hi, I am having the same issue. I followed the same processed as describied above but I am still getting “error ‘admin_url’ is not defined no-undef” when trying to compile.
I added the following line in routes/common.js without success "
// eslint-disable-next-line no-undef
console.log(ajax_object);"
Any thought?
Here is my code:
// app/setup
add_action(‘wp_enqueue_scripts’, function () {
wp_enqueue_script(‘sage/main.js’, asset_path(‘scripts/main.js’), [‘jquery’], null, true);
According to the eslint online documentation https://eslint.org/docs/rules/no-undef
it seems like the js object “admin_url” declared in the wp_localize_script: wp_localize_script( ‘sage/main.js’, ‘admin_url’, array(
‘ajax_url’ => admin_url( ‘admin-ajax.php’ )
) );
has to be explicitly mentioned in a /global …/ comment. I tried to do the following in common.js: but I am not sure if it is the right way of getting around that “no-undef” lint error
You would need to add admin_url to the globals definition:
"globals": {
"wp": true,
"admin_url": true
},
The globals definition in your ESLint config is essentially telling ESLint “Please don’t check to see if the variables I’ve set to ‘true’ here are defined in my scripts: they will be globally available when the scripts run.”