如何在Require.js中正确使用Create.js?配置后出现createjs未定义错误
Hey there, let's break down why you're hitting that error and how to fix it. The core issue here is that EaselJS isn't an AMD-compatible module by default—so when you switched to using RequireJS's config instead of your original script tag approach, RequireJS doesn't know how to expose the createjs global variable to your modules.
Step 1: Update Your RequireJS Config with a Shim
You need to tell RequireJS two critical things about EaselJS:
- Where to locate the EaselJS file (via the
pathssetting) - What global variable it exports (via the
shimsetting)
Here's a sample config tailored to your setup (adjust paths to match your actual file structure):
requirejs.config({ baseUrl: 'js', // Set this to your root JavaScript directory paths: { 'easeljs': 'lib/easeljs.min' // Path to your EaselJS file (e.g., in a lib folder) }, shim: { 'easeljs': { exports: 'createjs' // Tell RequireJS this module exposes the `createjs` global } } }); // Load your main app module as before requirejs(["app/main"]);
Step 2: Import EaselJS in Your Main Module
In your app/main.js, you now need to explicitly include easeljs as a dependency. RequireJS will pass the exported createjs object to your module function, so you can use it directly without relying on a global variable:
define(['easeljs'], function(createjs) { // Now you can safely use createjs here const stage = new createjs.Stage('your-canvas-id'); // Rest of your app logic goes here... });
Why This Fixes the Error
Your original working setup likely loaded EaselJS via a regular <script> tag, which automatically adds createjs to the global window object. When you removed that tag and switched to RequireJS, without the shim config, RequireJS loads EaselJS but doesn't make its variables accessible to your modules. The shim bridges this gap by mapping the module to its global export.
Quick double-check: Make sure your paths setting points to the correct EaselJS file location relative to your baseUrl—incorrect file paths are a super common gotcha here!
内容的提问来源于stack exchange,提问作者Rick Tschudin

