UNPKG

tpack-requirejs

Version:

TPack 插件:使用 requirejs 打包 AMD 模块。

80 lines (71 loc) 2.88 kB
/* * Copyright (C) 2016 xuld<xuld@vip.qq.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: *  * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var Path = require("path"); var RequireJS = require("requirejs"); var Desync = require("deasync"); /** * 打包 AMD 模块。 * @param {BuildFile} file 要生成的文件。 * @param {Object} options 相关的选项。 * @see https://github.com/jrburke/requirejs */ module.exports = function requireJS(file, options) { // 设置默认值。 options = Object.assign({ optimize: "none", generateSourceMaps: !!file.sourceMap, baseUrl: file.builder.srcPath }, options); options.baseUrl = file.builder.toPath(options.baseUrl); if (!options.name) { options.name = Path.relative(options.baseUrl, file.srcPath).replace(/\\/g, "/").replace(/\.\w+$/, ""); } options.out = function (chunk, sourceMap) { file.content = chunk; if (sourceMap) { sourceMap = JSON.parse(sourceMap); sourceMap.sources = sourceMap.sources.map(function (path) { return Path.join(options.baseUrl, path); }); file.applySourceMap(sourceMap); } }; // 生成。 var requirejsEnd = false; RequireJS.optimize(options, function () { requirejsEnd = true; }, function (e) { requirejsEnd = true; var fileNameMatch = /for file: (.+?)\n/.exec(e.message); var lineMatch = /Error: Line (\d+?):/.exec(e.message); e.name = "RequireJS" + e.name; if (fileNameMatch) e.fileName = fileNameMatch[1]; if (lineMatch) e.startLine = lineMatch[1]; file.error(e); }); // 等待打包完成。 while (!requirejsEnd) { Desync.sleep(100); } };