在WordPress中集成Anime.js遇module未定义错误求助
The error you're hitting boils down to a simple mismatch: the version of anime.js you're using is built as a CommonJS module (made for Node.js environments), but WordPress loads scripts in a browser context where module.exports isn't supported. Let's walk through the most reliable fixes, step by step:
1. Switch to a Browser-Compatible anime.js Build (Recommended)
The easiest and most maintainable fix is to use the UMD/IIFE version of anime.js, which is designed to work seamlessly in browsers. You have two options here:
- Use a CDN: Replace your local anime.js file with a CDN link that serves the browser-friendly build.
- Download the correct local file: Grab
anime.min.jsfrom the official anime.js releases page (skip theanime.cjs.jsoranime.es.jsbuilds—those are module-only for Node/ES module environments).
Updated functions.php Code
Replace your existing script-loading function with this example (using a CDN for simplicity):
function load_my_scripts() { // Enqueue browser-compatible anime.js from CDN wp_register_script('animejs', 'https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js', array(), '3.2.1', true ); wp_enqueue_script('animejs'); // Enqueue your custom script (depends on animejs) wp_register_script('scriptjs', get_template_directory_uri() . "/js/script.js", array('animejs'), '', true ); wp_enqueue_script('scriptjs'); } // Use wp_enqueue_scripts instead of init (proper hook for front-end scripts) add_action('wp_enqueue_scripts', 'load_my_scripts');
I also swapped the init hook for wp_enqueue_scripts—this is the standard WordPress hook for loading front-end scripts, ensuring everything loads at the right time in the page lifecycle.
2. Quick Fix: Modify Your Local anime.js File (Not Recommended for Updates)
If you need to stick with your local anime.js file, edit the very last line to replace the module export with a global browser variable:
Before:
module.exports = anime;
After:window.anime = anime;
This makes the anime object available globally in the browser, so your custom script can access it without module errors. Just note: if you update anime.js later, you'll have to reapply this change.
3. Use ES Modules (Modern Browsers Only)
If you prefer using ES modules for cleaner imports, you can add the type="module" attribute to your scripts. Add this filter to your functions.php:
function add_module_attribute($tag, $handle) { // Apply module type to anime.js and your custom script if ('animejs' === $handle || 'scriptjs' === $handle) { return str_replace('type="text/javascript"', 'type="module"', $tag); } return $tag; } add_filter('script_loader_tag', 'add_module_attribute', 10, 2);
Then update your script.js to import anime directly:
import anime from './anime.js'; // Rest of your animation code goes here...
Keep in mind: this only works in modern browsers, and you'll need to make sure the file paths in your import match WordPress's script URL structure.
内容的提问来源于stack exchange,提问作者Julian

