1 | var rRequireNull = /\brequire\s*\(\s*('|")this_should_be_null\1\s*\)/ig;
|
2 | var rComment = /"(?:[^\\"\r\n\f]|\\[\s\S])*"|'(?:[^\\'\n\r\f]|\\[\s\S])*'|(\/\/[^\r\n\f]+|\/\*[\s\S]+?(?:\*\/|$))/;
|
3 | var opts = {};
|
4 |
|
5 | var 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 |
|
17 | var 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 |
|
28 | module.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 |
|
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 |
|
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 |
|
71 | module.exports.init = function(options) {
|
72 | opts = options || {};
|
73 | };
|
74 |
|