HomeBlog
Wrapping Third-Party Libraries for RequireJS : Polyvia - 羡辙杂俎
2015.06.13 22:42:58
Wrapping Third-Party Libraries for RequireJS

Series: Polyvia

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

From RequireJS

Third-Party libraries sometimes come without AMD version. This post introduces a method to wrap them using shim. I’m going to take Three.js as example. The file structure is shown below. three.js and three.EdgeShader.js are required in A.js, and the later of which depends on the former one.

index.html
    /vendor
        three.js
        three.EdgeShader.js
    /src
        /js
            A.js

In index.html, we use shim for three and threeEdge. The deps attribute of threeEdge denotes the dependence on three, and exports makes THREE and THREE.EdgeShader accessible elsewhere.

require.config({
    baseUrl: './src/js',
    paths: {
        'three': '../../vendor/three',
        'threeEdge': '../../vendor/three.EdgeShader',
    },
    shim: {
        'three': {
            exports: 'THREE'
        },
        'threeEdge': {
            deps: ['three'],
            exports: 'THREE.EdgeShader'
        }
    }
});

In A.js, they can be accessed by calling require('three') and require('threeEdge').

var THREE = require('three');
THREE.EdgeShader = require('threeEdge');
博文对你有帮助吗?如果有的话,要不要送我一本书呢?:heart_eyes:

Series: Polyvia


微信公众号“羡辙部落格”(xianzheblog)提供本站优质非技术类博文推送。

Creative Commons License
Every blog post in this site by Wenli Zhang is licensed under a CC 3.0 License, based on a work at Github. You can see the source code of this blog site at github.com/Ovilia/blog.

Comments

comments powered by Disqus