6

I try to add to my custom wordpress Theme requirejs because I do not want to use wp_enqueue over and over to inject used plugins and on the other side I do not want to mess the DOM from the beginning.

I followed a lot of tutorials what I got from google but none of theme is working. Is there a good working example how to use requirejs in a wrodpress theme properly?

3
  • 1
    I haven't ever used require in a WordPress project, but, you might try something like using grunt concatenation/minification so you can use a lot of js files for development, but only have to do a single wp_enqueue_script in your functions.php (or wherever). That's what I usually do anyway if I'm doing a project that is going to be js heavy (for WordPress anyway). Commented Apr 24, 2015 at 1:25
  • 1
    Between I managed like adding manually require.js to the footer and call the main file over requires config file.
    – fefe
    Commented Apr 24, 2015 at 7:54
  • 1
    You enqueue requirejs as one file, then your main entry file as another with the requirejs dependency.
    – kontur
    Commented Oct 15, 2017 at 18:49

1 Answer 1

0

You can use require (commonJS modules) or import/export (ESM), and you can even mix both in the same project ("hybrid package" based on sub-folders). You will need a build tool to handle imports if you want to ensure cross-browser compatibility.

I have been using esbuild in a recent project as a lightweight alternative to webpack but you can choose any builder that can combine multiple script files into one single output file.

Then you will only need one enqueue script directive.

Install esbuild:

npm install --save-dev esbuild

and use it in your build target e.g. in package.json:

  "scripts": {
    "build": "build:core build:postcss build:js",
    "build:js": "esbuild src/js/scripts.js --bundle --sourcemap --target=es5 --outfile=themes/mytheme/js/scripts.js",
  },
  "type": "commonjs",

or change to "type": "module" to use import instead of require.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.