简体   繁体   中英

how do I determine if a JS file is AMD-compatible?

I'm using curl or require (evaluating both) to load js files asynchronously. I'm using 5 js files in my prototyping app:

jquery.min.js // off of CDN
Bacon.js // reactive programming tool
curl.js  // js loader
index.coffee // page specific
foo.coffee // app specific

OK, so I built index.coffee and foo.coffee , so I'm pretty sure those aren't AMD compatible. Could be wrong though, since foo.coffee has

if module? && module.exports?
  module.exports = Foo

at the end.

How do I look at a js file and say 'Yes, AMD' or 'No, not AMD'?

Look for the define( signature of AMD. That's a fairly sure bet. It can be almost anywhere in the file, unfortunately. It's typically at the top or the bottom. There are many variations of AMD modules and several UMD module formats, too: https://github.com/umdjs/umd and https://gist.github.com/unscriptable/4118495 .

Fwiw, you can use raw CommonJS modules with curl.js, as well. You have to place your CJS modules into a folder and tell curl that it's a package that uses CJS modules:

curl.config({
    packages: [
        { name: 'foo', location: 'path/to/foo-folder', main: 'foo',
            config: { moduleLoader: 'curl/loader/cjsm11' }
        },
        { name: 'curl', location: 'path/to/curl/src/curl', main: 'curl' }
    ]
});

You need the curl package (or a path) to tell curl where to find curl/loader/cjsm11.

AMD means, that you evaluate code as you need to, not at the moment it loads. So if your code executes right after downloading - it's not AMD. If it has a wrapper around it, allowing the code to be executed by demand - it can act like AMD module.

If you're looking for exact AMD API , you should search for define word at the beginning of your file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM