вторник, 21 февраля 2017 г.

RequireJS with Babel 6 and Babel 5 standalone

Файл index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="require.js"></script>
    <script type="text/javascript" src="require-config.js"></script>
    <title>RequireJS Babel</title>
</head>
<body>
    <script type="text/javascript">
        require(['index']);
    </script>
</body>
</html>

Файл require.js --> RequireJS 2.3.3: https://github.com/requirejs/requirejs

Файл require-config.js

requirejs.config({
      config: {
        es6: {
            resolveModuleSource: function (source) {
                return 'es6!' + source;
            }
        }
      }
    , baseUrl: './'
    , urlArgs: 'version=' + 100
    , shim: {
          es6shim: {deps: ['es5shim']}
      }
    , paths: {
          es6: 'es6'
        , babel: 'babel'
        , index: 'index'
      }
});

Файл es6.js --> es6.js with fix for Babel 6 from https://github.com/mikach/requirejs-babel

var fetchText, _buildMap = {};

//>>excludeStart('excludeBabel', pragmas.excludeBabel)
if (typeof window !== "undefined" && window.navigator && window.document) {
    fetchText = function (url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function (evt) {
            //Do not explicitly handle errors, those should be
            //visible via console output in the browser.
            if (xhr.readyState === 4) {
                callback(xhr.responseText);
            }
        };
        xhr.send(null);
    };
} else if (typeof process !== "undefined" &&
           process.versions &&
           !!process.versions.node) {
    //Using special require.nodeRequire, something added by r.js.
    fs = require.nodeRequire('fs');
    fetchText = function (path, callback) {
        callback(fs.readFileSync(path, 'utf8'));
    };
}
//>>excludeEnd('excludeBabel')

define([
    //>>excludeStart('excludeBabel', pragmas.excludeBabel)
    'babel',
    //>>excludeEnd('excludeBabel')
    'module'
], function(
    //>>excludeStart('excludeBabel', pragmas.excludeBabel)
    babel,
    //>>excludeEnd('excludeBabel')
    _module
    ) {
    return {
        load: function (name, req, onload, config) {
            //>>excludeStart('excludeBabel', pragmas.excludeBabel)
            function applyOptions(options) {
                var defaults = {
                    plugins: ['transform-es2015-modules-amd'], // modules: 'amd' <-- for Babel 5 || plugins: ['transform-es2015-modules-amd'] <-- for Babel 6
                    sourceMap: config.isBuild ? false :'inline',
                    sourceFileName: name + '.js'
                };
                for(var key in options) {
                    if(options.hasOwnProperty(key)) {
                        defaults[key] = options[key];
                    }
                }
                return defaults;
            }
            var url = req.toUrl(name + '.js');

            fetchText(url, function (text) {
                var code = babel.transform(text, applyOptions(_module.config())).code;

                if (config.isBuild) {
                    _buildMap[name] = code;
                }

                onload.fromText(code);
            });
            //>>excludeEnd('excludeBabel')
        },

        write: function (pluginName, moduleName, write) {
            if (moduleName in _buildMap) {
                write.asModule(pluginName + '!' + moduleName, _buildMap[moduleName]);
            }
        }
    }
});

Файл babel.js --> babel-standalone for Babel 6 from https://github.com/babel/babel-standalone
or Babel 5 from https://github.com/mikach/requirejs-babel

Файл index.js

define(function (require) {
    var cl = require('es6!class');
    const a = 12345;
    alert(a);
});

Файл class.js

import sum from 'sum';

alert(sum(1, 2));

class A {
    constructor (a) {
        alert('Hello ' + a);
    }
}

new A('world!');

Файл sum.js

export default (a, b) => a + b;

---------------------------------------

Файл es6.js with fix for Babel 6 and R.js

// For Browser

// Define paths:

// require.config({
//       'es6': 'node_modules/requirejs-es6/index'
//     , 'babel-core': 'node_modules/requirejs-es6/node_modules/babel-core/browser.min'
// });

// Then use as a normal RequireJS plugin:

// require(['es6!path/to/MyEs6File'], function (MyEs6File) {
//     var myfile = new MyEs6File();
//     ...
// });

// For Server

// To use your existing client-side AMD modules in node, use global-define and set the path to the requirejs-es6 module.
// This so that when RequireJS tries to resolve the module name, it maps to the correct package.

// require('global-define')({
//       basePath: __dirname
//     , paths: {
//         'es6': 'requirejs-es6'
//       }
// });

;(function () {

    var fetchText
        , _buildMap = {}
        , fs;

    function isBrowser () {return typeof window !== 'undefined' && window.navigator && window.document;}
    function isNode () {return typeof process !== 'undefined' && process.versions && !!process.versions.node;}
    function isRequireBuildProcess () {return isNode() && require.nodeRequire;}

    if (isBrowser()) {
        fetchText = function (url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function () {
                // Do not explicitly handle errors, those should be visible via console output in the browser.
                if (xhr.readyState === 4) {callback(xhr.responseText);}
            };
            xhr.send(null);
        };
    } else if (isRequireBuildProcess()) {
        fs = require.nodeRequire('fs'); // nodeRequire is a method added by r.js
        fetchText = function (path, callback) {
            callback(fs.readFileSync(path, 'utf8'));
        };
    } else if (isNode()) {
        fs = require('fs');
        fetchText = function (path, callback) {
            callback(fs.readFileSync(path, 'utf8'));
        };
    }

    define(['babel', 'module'], function(babel, _module) {
        return {
              load: function (name, req, onload, config) {
                function applyOptions (options) {
                    var defaults = {
                          plugins: ['transform-es2015-modules-amd'] // modules: 'amd' <-- for Babel 5 || plugins: ['transform-es2015-modules-amd'] <-- for Babel 6
                        , sourceMap: config.isBuild ? false :'inline'
                        , sourceFileName: name + '.js'
                    };
                    for (var key in options) {
                        if (options.hasOwnProperty(key)) {defaults[key] = options[key];}
                    }
                    return defaults;
                }
                var url = req.toUrl(name + '.js');
                fetchText(url, function (text) {
                    var babelConfig = _module.config ? _module.config() : {};
                    var code = babel.transform(text, applyOptions(babelConfig)).code;
                    if (config.isBuild) {_buildMap[name] = code;}
                    if (isNode() && !config.isBuild) {
                        var fileName = name + '.tmp';
                        fs.writeFileSync(fileName, code);
                        onload(req(fileName));
                        fs.unlink(fileName);
                    } else {
                        onload.fromText(code);
                    }
                });
              }
            , write: function (pluginName, moduleName, write) {
                if (moduleName in _buildMap) {write.asModule(pluginName + '!' + moduleName, _buildMap[moduleName]);}
              }
        };
    });

})();

1 комментарий:

  1. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here
    Thank you. Your blog was very helpful and efficient For Me,Thanks for Sharing the information Regards..!!..AngularJS 5 Online Training

    ОтветитьУдалить