Skip to content
This repository was archived by the owner on Aug 7, 2021. It is now read-only.

Commit c756b46

Browse files
committed
refactor: move plugins to separate dir
1 parent 4efad00 commit c756b46

14 files changed

Lines changed: 260 additions & 211 deletions

index.js

Lines changed: 9 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,19 @@
1-
const sources = require("webpack-sources");
2-
const fs = require("fs");
31
const path = require("path");
2+
const { existsSync } = require("fs");
43

5-
const { isAngular, getPackageJson } = require("./projectHelpers");
4+
const { getPackageJson, isAngular } = require("./projectHelpers");
5+
const { sanitize } = require("./utils");
66

77
const PROJECT_DIR = path.dirname(path.dirname(__dirname));
88
const APP_DIR = path.join(PROJECT_DIR, "app");
99

10-
if (isAngular(PROJECT_DIR)) {
11-
exports.UrlResolvePlugin = require("./resource-resolver-plugins/UrlResolvePlugin");
12-
}
13-
14-
//HACK: changes the JSONP chunk eval function to `global["nativescriptJsonp"]`
15-
// applied to tns-java-classes.js only
16-
exports.NativeScriptJsonpPlugin = function () {
17-
};
18-
19-
exports.NativeScriptJsonpPlugin.prototype.apply = function (compiler) {
20-
compiler.plugin("compilation", function (compilation) {
21-
compilation.plugin("optimize-chunk-assets", function (chunks, callback) {
22-
chunks.forEach(function (chunk) {
23-
chunk.files.forEach(function (file) {
24-
if (file === "vendor.js") {
25-
const src = compilation.assets[file];
26-
const code = src.source();
27-
const match = code.match(/window\["nativescriptJsonp"\]/);
28-
if (match) {
29-
compilation.assets[file] = new sources.ConcatSource(code.replace(/window\["nativescriptJsonp"\]/g, "global[\"nativescriptJsonp\"]"));
30-
}
31-
}
32-
});
33-
});
34-
callback();
35-
});
36-
});
37-
};
38-
39-
exports.GenerateBundleStarterPlugin = function (bundles) {
40-
this.bundles = bundles;
41-
};
42-
43-
exports.GenerateBundleStarterPlugin.prototype = {
44-
apply: function (compiler) {
45-
const plugin = this;
46-
plugin.webpackContext = compiler.options.context;
47-
48-
compiler.plugin("emit", function (compilation, cb) {
49-
compilation.assets["package.json"] = plugin.generatePackageJson();
50-
compilation.assets["starter.js"] = plugin.generateStarterModule();
51-
plugin.generateTnsJavaClasses(compilation);
10+
Object.assign(exports, require('./plugins').commonPlugins);
5211

53-
cb();
54-
});
55-
},
56-
generateTnsJavaClasses: function (compilation) {
57-
const path = compilation.compiler.outputPath;
58-
const isAndroid = path.indexOf("android") > -1;
59-
60-
if (isAndroid && !compilation.assets["tns-java-classes.js"]) {
61-
compilation.assets["tns-java-classes.js"] = new sources.RawSource("");
62-
}
63-
},
64-
generatePackageJson: function () {
65-
const packageJson = getPackageJson(this.webpackContext);
66-
packageJson.main = "starter";
67-
68-
return new sources.RawSource(JSON.stringify(packageJson, null, 4));
69-
},
70-
generateStarterModule: function () {
71-
const moduleSource = this.bundles
72-
.map(bundle => `require("${bundle}")`)
73-
.join("\n");
12+
if (isAngular({projectDir: PROJECT_DIR})) {
13+
Object.assign(exports, require('./plugins').angularPlugins);
14+
}
7415

75-
return new sources.RawSource(moduleSource);
76-
},
77-
};
16+
exports.uglifyMangleExcludes = require("./mangle-excludes");
7817

7918
exports.getEntryModule = function () {
8019
const maybePackageJsonEntry = getPackageJsonEntry();
@@ -87,8 +26,6 @@ exports.getEntryModule = function () {
8726
};
8827

8928
exports.getAppPath = platform => {
90-
var projectDir = path.dirname(path.dirname(__dirname));
91-
9229
if (/ios/i.test(platform)) {
9330
const appName = path.basename(PROJECT_DIR);
9431
const sanitizedName = sanitize(appName);
@@ -101,8 +38,6 @@ exports.getAppPath = platform => {
10138
}
10239
};
10340

104-
exports.uglifyMangleExcludes = require("./mangle-excludes");
105-
10641
function getPackageJsonEntry() {
10742
const packageJsonSource = getPackageJson(APP_DIR);
10843
const entry = packageJsonSource.main;
@@ -114,6 +49,6 @@ function getAotEntry(entry) {
11449
const aotEntry = `${entry}.aot.ts`;
11550
const aotEntryPath = path.join(APP_DIR, aotEntry);
11651

117-
return fs.existsSync(aotEntryPath) ? aotEntry : null;
52+
return existsSync(aotEntryPath) ? aotEntry : null;
11853
}
11954

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const { RawSource } = require("webpack-sources");
2+
const { getPackageJson } = require("../projectHelpers");
3+
4+
exports.GenerateBundleStarterPlugin = (function() {
5+
function GenerateBundleStarterPlugin(bundles) {
6+
this.bundles = bundles;
7+
};
8+
9+
GenerateBundleStarterPlugin.prototype.apply = function(compiler) {
10+
const plugin = this;
11+
plugin.webpackContext = compiler.options.context;
12+
13+
compiler.plugin("emit", function (compilation, cb) {
14+
compilation.assets["package.json"] = plugin.generatePackageJson();
15+
compilation.assets["starter.js"] = plugin.generateStarterModule();
16+
plugin.generateTnsJavaClasses(compilation);
17+
18+
cb();
19+
});
20+
}
21+
22+
GenerateBundleStarterPlugin.prototype.generateTnsJavaClasses = function (compilation) {
23+
const path = compilation.compiler.outputPath;
24+
const isAndroid = path.indexOf("android") > -1;
25+
26+
if (isAndroid && !compilation.assets["tns-java-classes.js"]) {
27+
compilation.assets["tns-java-classes.js"] = new RawSource("");
28+
}
29+
}
30+
31+
GenerateBundleStarterPlugin.prototype.generatePackageJson = function () {
32+
const packageJson = getPackageJson(this.webpackContext);
33+
packageJson.main = "starter";
34+
35+
return new RawSource(JSON.stringify(packageJson, null, 4));
36+
}
37+
38+
GenerateBundleStarterPlugin.prototype.generateStarterModule = function () {
39+
const moduleSource = this.bundles
40+
.map(bundle => `require("${bundle}")`)
41+
.join("\n");
42+
43+
return new RawSource(moduleSource);
44+
}
45+
46+
return GenerateBundleStarterPlugin;
47+
})();

plugins/NativeScriptJsonpPlugin.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const { ConcatSources } = require("webpack-sources");
2+
3+
const WINDOWS_GLOBAL_MATCHER = /window\["nativescriptJsonp"\]/g;
4+
const NATIVESCRIPT_GLOBAL = "global[\"nativescriptJsonp\"]";
5+
const isVendorChunk = name => name === "vendor.js";
6+
7+
//HACK: changes the JSONP chunk eval function to `global["nativescriptJsonp"]`
8+
// applied to tns-java-classes.js only
9+
exports.NativeScriptJsonpPlugin = (function() {
10+
function NativeScriptJsonpPlugin() {
11+
}
12+
13+
NativeScriptJsonpPlugin.prototype.apply = function (compiler) {
14+
compiler.plugin("compilation", function (compilation) {
15+
compilation.plugin("optimize-chunk-assets", function (chunks, callback) {
16+
chunks.forEach(function (chunk) {
17+
chunk.files
18+
.filter(isVendorChunk)
19+
.forEach(file => replaceGlobal(compilation.assets, file));
20+
});
21+
callback();
22+
});
23+
});
24+
};
25+
26+
return NativeScriptJsonpPlugin;
27+
})();
28+
29+
function replaceGlobal(assets, file) {
30+
const path = assets[file];
31+
const source = path.source();
32+
const match = source.match(WINDOWS_GLOBAL_MATCHER);
33+
34+
if (match) {
35+
const newSource = source.replace(WINDOWS_GLOBAL_MATCHER, NATIVESCRIPT_GLOBAL);
36+
assets[file] = new ConcatSource(newSource);
37+
}
38+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
const { resolve, join } = require("path");
2+
const { closeSync, openSync } = require("fs");
3+
4+
const ProjectSnapshotGenerator = require("../snapshot/android/project-snapshot-generator");
5+
6+
exports.NativeScriptSnapshotPlugin = (function() {
7+
function NativeScriptSnapshotPlugin(options) {
8+
ProjectSnapshotGenerator.call(this, options); // Call the parent constructor
9+
10+
if (!this.options.chunk) {
11+
throw new Error("No chunk specified.");
12+
}
13+
14+
console.dir()
15+
16+
if (this.options.webpackConfig) {
17+
if (this.options.webpackConfig.output && this.options.webpackConfig.output.libraryTarget) {
18+
this.options.webpackConfig.output.libraryTarget = undefined;
19+
}
20+
21+
if (this.options.webpackConfig.entry) {
22+
if (typeof this.options.webpackConfig.entry === "string" ||
23+
this.options.webpackConfig.entry instanceof Array)
24+
this.options.webpackConfig.entry = { bundle: this.options.webpackConfig.entry };
25+
}
26+
27+
this.options.webpackConfig.entry["tns-java-classes"] = this.getTnsJavaClassesBuildPath();
28+
}
29+
}
30+
31+
// inherit ProjectSnapshotGenerator
32+
NativeScriptSnapshotPlugin.prototype = Object.create(ProjectSnapshotGenerator.prototype);
33+
NativeScriptSnapshotPlugin.prototype.constructor = NativeScriptSnapshotPlugin;
34+
35+
NativeScriptSnapshotPlugin.prototype.getTnsJavaClassesBuildPath = function() {
36+
return resolve(this.getBuildPath(), "../tns-java-classes.js");
37+
}
38+
39+
NativeScriptSnapshotPlugin.prototype.generate = function(webpackChunk) {
40+
const options = this.options;
41+
42+
const inputFile = join(options.webpackConfig.output.path, webpackChunk.files[0]);
43+
44+
console.log(`\n Snapshotting bundle at ${inputFile}`);
45+
46+
const preparedAppRootPath = join(options.projectRoot, "platforms/android/src/main/assets");
47+
const preprocessedInputFile = join(preparedAppRootPath, "app/_embedded_script_.js");
48+
49+
ProjectSnapshotGenerator.prototype.generate.call(this, {
50+
inputFile,
51+
preprocessedInputFile,
52+
targetArchs: options.targetArchs,
53+
useLibs: options.useLibs,
54+
androidNdkPath: options.androidNdkPath,
55+
tnsJavaClassesPath: join(preparedAppRootPath, "app/tns-java-classes.js")
56+
});
57+
58+
// Make the original file empty
59+
if (inputFile !== preprocessedInputFile) {
60+
closeSync(openSync(inputFile, "w")); // truncates the input file content
61+
}
62+
}
63+
64+
NativeScriptSnapshotPlugin.prototype.apply = function(compiler) {
65+
const options = this.options;
66+
67+
// Generate tns-java-classes.js file
68+
debugger;
69+
ProjectSnapshotGenerator.prototype.generateTnsJavaClassesFile.call(this, {
70+
output: this.getTnsJavaClassesBuildPath(),
71+
options: options.tnsJavaClassesOptions
72+
});
73+
74+
// Run the snapshot tool when the packing is done
75+
compiler.plugin("done", function(result) {
76+
debugger;
77+
const chunkToSnapshot = result.compilation.chunks.find(chunk => chunk.name == options.chunk);
78+
if (!chunkToSnapshot) {
79+
throw new Error(`No chunk named '${options.chunk}' found.`);
80+
}
81+
82+
this.generate(chunkToSnapshot);
83+
84+
}.bind(this));
85+
}
86+
87+
return NativeScriptSnapshotPlugin;
88+
})();

resource-resolver-plugins/UrlResolvePlugin.js renamed to plugins/UrlResolvePlugin.js

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
const ts = require("typescript");
2-
const fs = require("fs");
3-
const path = require("path");
1+
const { forEachChild, SyntaxKind } = require("typescript");
2+
const { existsSync } = require("fs");
3+
const { resolve } = require("path");
44

5-
const UrlResolvePlugin = (function() {
5+
exports.UrlResolvePlugin = (function() {
66
function UrlResolvePlugin(options) {
77
if (!options || !options.platform) {
88
throw new Error(`Target platform must be specified!`);
@@ -40,15 +40,15 @@ const UrlResolvePlugin = (function() {
4040

4141
UrlResolvePlugin.prototype.usePlatformUrl = function(sourceFile) {
4242
this.setCurrentDirectory(sourceFile);
43-
ts.forEachChild(sourceFile, node => this.traverseDecorators(node));
43+
forEachChild(sourceFile, node => this.traverseDecorators(node));
4444
}
4545

4646
UrlResolvePlugin.prototype.setCurrentDirectory = function(sourceFile) {
47-
this.currentDirectory = path.resolve(sourceFile.path, "..");
47+
this.currentDirectory = resolve(sourceFile.path, "..");
4848
}
4949

5050
UrlResolvePlugin.prototype.traverseDecorators = function(node) {
51-
if (node.kind !== ts.SyntaxKind.ClassDeclaration || !node.decorators) {
51+
if (node.kind !== SyntaxKind.ClassDeclaration || !node.decorators) {
5252
return;
5353
}
5454

@@ -90,9 +90,9 @@ const UrlResolvePlugin = (function() {
9090
}
9191

9292
UrlResolvePlugin.prototype.noMultiplatformFile = function(url) {
93-
let filePath = path.resolve(this.currentDirectory, url);
93+
let filePath = resolve(this.currentDirectory, url);
9494

95-
return !fs.existsSync(filePath);
95+
return !existsSync(filePath);
9696
}
9797

9898
UrlResolvePlugin.prototype.replaceUrlsValue = function(element) {
@@ -105,5 +105,3 @@ const UrlResolvePlugin = (function() {
105105

106106
return UrlResolvePlugin;
107107
})();
108-
109-
module.exports = UrlResolvePlugin;

plugins/index.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const commonPlugins = Object.assign({},
2+
require("./GenerateBundleStarterPlugin"),
3+
require("./NativeScriptJsonpPlugin"),
4+
require("./NativeScriptSnapshotPlugin")
5+
);
6+
7+
const angularPlugins = Object.assign({},
8+
require("./UrlResolvePlugin")
9+
);
10+
11+
module.exports = {
12+
commonPlugins,
13+
angularPlugins,
14+
};

prepublish/common/exports.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ module.exports = env => {
2222
const plugins = getPlugins(platform, env);
2323
const extensions = getExtensions(platform);
2424
25-
return {
25+
const config = {
2626
context: resolve("./app"),
2727
target: nativescriptTarget,
2828
entry,
@@ -51,6 +51,18 @@ module.exports = env => {
5151
module: { rules },
5252
plugins,
5353
};
54+
55+
if (env.snapshot) {
56+
plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({
57+
chunk: "vendor",
58+
projectRoot: __dirname,
59+
webpackConfig: config,
60+
targetArchs: ["arm", "arm64"],
61+
tnsJavaClassesOptions: { packages: ["tns-core-modules" ] },
62+
useLibs: false
63+
}));
64+
}
65+
66+
return config;
5467
};
5568
`;
56-

prepublish/common/uglify.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
module.exports = `
2-
if (env.uglify) {
1+
module.exports = `if (env.uglify) {
32
plugins.push(new webpack.LoaderOptionsPlugin({ minimize: true }));
43
54
// Work around an Android issue by setting compress = false
@@ -8,4 +7,5 @@ module.exports = `
87
mangle: { except: nsWebpack.uglifyMangleExcludes },
98
compress,
109
}));
11-
}`;
10+
}
11+
`;

0 commit comments

Comments
 (0)