I know what a "constant" is and I know "import" from php. I read many tutorials I and found both types of importing dependencies:
import { useSelect, AsyncModeProvider } from '@wordpress/data';
and
const useSelect = wp.data.useSelect;
const AsyncModeProvider = wp.data.AsyncModeProvider;
both seem to work. But which one should I use?
I know what a "constant" is and I know "import" from php. I read many tutorials I and found both types of importing dependencies:
import { useSelect, AsyncModeProvider } from '@wordpress/data';
and
const useSelect = wp.data.useSelect;
const AsyncModeProvider = wp.data.AsyncModeProvider;
both seem to work. But which one should I use?
Share Improve this question asked Jan 6, 2021 at 11:47 MarcMarc 6979 silver badges28 bronze badges 3- The answer to this depends on how your code is built, how are you building your code? Are you using WP Scripts? – Tom J Nowell ♦ Commented Jan 6, 2021 at 12:16
- Since I don't know I guess not? You mean this? developer.wordpress/block-editor/packages/packages-scripts I only use a few of this imports: github/mtoensing/simpletoc/blob/3.5/src/index.js but no wp scripts. – Marc Commented Jan 6, 2021 at 12:20
- Yes, you're using WP Scripts: github/mtoensing/simpletoc/blob/3.5/package.json#L8, update your question to mention this as it can mean the difference between an accurate and a wildly wrong answer – Tom J Nowell ♦ Commented Jan 6, 2021 at 12:26
1 Answer
Reset to default 4import
will import those items from a package. const
is just an indicator that a variable is a constant, a variable that cannot be reassigned. E.g. const number = 5;
.
In this case, these 2 lines do exactly the same thing:
const useSelect = wp.data.useSelect;
const useSelect = window.wp.data.useSelect;
The important difference being that if you had included a copy of the data package in your bundle, then used const useSelect = wp.data.useSelect;
it would not use that data package, it would use wp.data
as loaded by WordPress. The same as if you had written wp.data
in the browser console, or jQuery(document).ready(...
However, because you used WP Scripts, it has webpack set up not to include WordPress packages from a predefined list, and to instead use the already loaded versions. It generates a PHP file with scripts to enqueue that the built bundle needs to run.
So for your purposes, always use import
.