UNPKG

2.23 kBJavaScriptView Raw
1var rRequireNull = /\brequire\s*\(\s*('|")this_should_be_null\1\s*\)/ig;
2var rComment = /"(?:[^\\"\r\n\f]|\\[\s\S])*"|'(?:[^\\'\n\r\f]|\\[\s\S])*'|(\/\/[^\r\n\f]+|\/\*[\s\S]+?(?:\*\/|$))/;
3var opts = {};
4
5var vars = {
6 'Buffer': function() {
7 return 'var Buffer = require("buffer").Buffer;';
8 },
9 'Buffer.isBuffer': function() {
10 return 'Buffer.isBuffer = require("is-buffer");';
11 },
12 process: function () {
13 return 'var process = require(\'process/browser\');';
14 }
15};
16
17var replaceVars = {
18 __filename: function (file, basedir) {
19 var filename = file.subpath;
20 return JSON.stringify(filename);
21 },
22 __dirname: function (file, basedir) {
23 var dir = file.subdirname;
24 return JSON.stringify(dir);
25 }
26}
27
28module.exports = function(content, file) {
29 content = content.replace(rRequireNull, 'null');
30
31 function append(str) {
32 content = [content, str].join('\n');
33 }
34
35 function prepend(str) {
36 content = [str, content].join('\n');
37 }
38
39 Object.keys(replaceVars).forEach(function (name) {
40 var reg = new RegExp(fis.util.escapeReg(name), 'g');
41 content = content.replace(reg, typeof replaceVars[name] === 'function' ? replaceVars[name](file) : replaceVars[name]);
42 });
43
44 Object.keys(vars).forEach(function (name) {
45 var reg = new RegExp(rComment.source + '|[^\\.]\\b(' + name + ')\\b', 'g');
46 var attched = false;
47
48 // 避免模块内部自己 require 自己
49 if (file.subpath.match(new RegExp('node_modules\/' + name + '\\b'))) {
50 return;
51 }
52
53 // 过滤掉在注释中的情况.
54 content.replace(reg, function(_, comment, matched) {
55 if (matched && !attched) {
56 prepend(vars[name](file));
57 attched = true;
58 }
59 });
60 });
61
62 // process 设置process.env.NODE_ENV
63 if (file.subpath.match(/node_modules\/process\/browser\b/)) {
64 var env = opts.env || (fis.project.currentMedia().match(/^dev/) ? 'development' : 'production');
65 append('process.env.NODE_ENV = "' + env + '"');
66 }
67
68 return content;
69}
70
71module.exports.init = function(options) {
72 opts = options || {};
73};
74