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

refactor: use webpack context when notifying CLI for changed files #455

Merged
merged 12 commits into from
Mar 10, 2018
2 changes: 1 addition & 1 deletion bin/ns-verify-bundle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const fs = require("fs");

const { getProjectDir } = require("../projectHelpers");

const PROJECT_DIR = getProjectDir({ nestingLvl: 2 });
const PROJECT_DIR = getProjectDir();
const APP_ID = require(path.resolve(PROJECT_DIR, "./package.json")).nativescript.id;
const APP_NAME = APP_ID.substring(APP_ID.lastIndexOf(".") + 1);
const PROJECT_PATHS = {
Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const { existsSync } = require("fs");

const { getPackageJson, getProjectDir, isAngular, resolveAndroidAppPath } = require("./projectHelpers");

const PROJECT_DIR = getProjectDir({ nestingLvl: 2 });
const PROJECT_DIR = getProjectDir();
const APP_DIR = path.join(PROJECT_DIR, "app");

Object.assign(exports, require('./plugins'));
Expand Down
2 changes: 1 addition & 1 deletion installer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const helpers = require("./projectHelpers");
const projectFilesManager = require("./projectFilesManager");
const dependencyManager = require("./dependencyManager");

const PROJECT_DIR = helpers.getProjectDir({ nestingLvl: 2 });
const PROJECT_DIR = helpers.getProjectDir();
const APP_DIR = path.resolve(PROJECT_DIR, "app");

function install() {
Expand Down
22 changes: 11 additions & 11 deletions lib/before-prepareJS.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
const { runWebpackCompiler } = require("./compiler");

module.exports = function ($mobileHelper, $projectData, $logger, hookArgs) {
const env = hookArgs.config.env || {};
const platform = hookArgs.config.platform;
const appFilesUpdaterOptions = hookArgs.config.appFilesUpdaterOptions;
const config = {
env,
platform,
bundle: appFilesUpdaterOptions.bundle,
release: appFilesUpdaterOptions.release,
};
const result = config.bundle && runWebpackCompiler.bind(runWebpackCompiler, config, $mobileHelper, $projectData, $logger, hookArgs);
return result;
const env = hookArgs.config.env || {};
const platform = hookArgs.config.platform;
const appFilesUpdaterOptions = hookArgs.config.appFilesUpdaterOptions;
const config = {
env,
platform,
bundle: appFilesUpdaterOptions.bundle,
release: appFilesUpdaterOptions.release,
};
const result = config.bundle && runWebpackCompiler.bind(runWebpackCompiler, config, $mobileHelper, $projectData, $logger, hookArgs);
return result;
}
41 changes: 29 additions & 12 deletions lib/before-watchPatterns.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
const { AppDirectoryLocation } = require("./constants");
const { basename } = require("path");
const { buildEnvData, getCompilationContext } = require("./utils");

module.exports = function (hookArgs) {
if (hookArgs.liveSyncData && hookArgs.liveSyncData.bundle) {
return (args, originalMethod) => {
return originalMethod(...args).then(originalPatterns => {
const appDirectoryLocationIndex = originalPatterns.indexOf(AppDirectoryLocation);
if (appDirectoryLocationIndex !== -1) {
originalPatterns.splice(appDirectoryLocationIndex, 1);
}
const { liveSyncData } = hookArgs;
if (!liveSyncData || !liveSyncData.bundle) {
return;
}

return originalPatterns;
});
};
}
const { platforms } = hookArgs;
const { env } = liveSyncData;
return (args, originalMethod) => {
return originalMethod(...args).then(originalPatterns => {
if (!platforms || !platforms.length) {
throw new Error("Target platform should be specified!");
}

const compilationContexts = platforms.map(platform =>
getContext(platform, env));

const ignorePatterns = compilationContexts.map(
context => `!${context}`
);

return [...originalPatterns, ...ignorePatterns];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The old logic spliced the unneeded watch pattern, whereas the new logic adds an exclusion and retains the originalPatterns.
Whenever we have ["app", "app/App_Resources", "!app"] in watch patterns - does this work as expected?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed in person.

});
};
}

function getContext(platform, env) {
const fullEnvData = buildEnvData(platform, env);
return getCompilationContext(fullEnvData);
}
13 changes: 10 additions & 3 deletions lib/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { join, resolve: pathResolve } = require("path");
const { existsSync } = require("fs");
const readline = require("readline");
const { messages } = require("../plugins/WatchStateLoggerPlugin");
const { AppDirectoryLocation } = require("./constants");
const { buildEnvData, getCompilationContext } = require("./utils");

let hasBeenInvoked = false;

Expand Down Expand Up @@ -41,7 +41,9 @@ exports.runWebpackCompiler = function runWebpackCompiler(config, $mobileHelper,
}

console.log(`Running webpack for ${config.platform}...`);
const envFlagNames = Object.keys(config.env).concat([config.platform.toLowerCase()]);

const envData = buildEnvData(config.platform, config.env);
const envFlagNames = Object.keys(envData);

const snapshotEnvIndex = envFlagNames.indexOf("snapshot");
if (snapshotEnvIndex !== -1 && !utils.shouldSnapshot($mobileHelper, config)) {
Expand Down Expand Up @@ -92,7 +94,12 @@ exports.runWebpackCompiler = function runWebpackCompiler(config, $mobileHelper,
}

if (hookArgs.filesToSync && hookArgs.startSyncFilesTimeout) {
hookArgs.filesToSync.push(...message.emittedFiles.map(emittedFile => join($projectData.projectDir, AppDirectoryLocation, emittedFile)));
const compilationContext = getCompilationContext(envData);
hookArgs.filesToSync.push(
...message.emittedFiles.map(
emittedFile => join($projectData.projectDir, compilationContext, emittedFile)
)
);
hookArgs.startSyncFilesTimeout();
}
}
Expand Down
3 changes: 0 additions & 3 deletions lib/constants.js

This file was deleted.

33 changes: 29 additions & 4 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,34 @@
const os = require("os");
const path = require("path");

const { getProjectDir, getWebpackConfig } = require("../projectHelpers");

function buildEnvData(platform, env) {
return Object.assign({},
env,
{ [platform.toLowerCase()]: true }
);
}

function getCompilationContext(env) {
const projectDir = getProjectDir();
const config = getWebpackConfig(projectDir, env);
const { context } = config;

return context ?
path.relative(projectDir, context) :
".";
}

function shouldSnapshot($mobileHelper, config) {
const platformSupportsSnapshot = $mobileHelper.isAndroidPlatform(config.platform);
const osSupportsSnapshot = os.type() !== "Windows_NT";
return config.bundle && config.release && platformSupportsSnapshot && osSupportsSnapshot;
const platformSupportsSnapshot = $mobileHelper.isAndroidPlatform(config.platform);
const osSupportsSnapshot = os.type() !== "Windows_NT";

return config.bundle && config.release && platformSupportsSnapshot && osSupportsSnapshot;
}

module.exports.shouldSnapshot = shouldSnapshot;
module.exports = {
buildEnvData,
getCompilationContext,
shouldSnapshot,
};
38 changes: 31 additions & 7 deletions projectHelpers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const path = require("path");
const fs = require("fs");
const semver = require("semver");
const { EOL } = require("os");

const isTypeScript = ({ projectDir, packageJson } = {}) => {
packageJson = packageJson || getPackageJson(projectDir);
Expand Down Expand Up @@ -44,6 +45,28 @@ const getAndroidRuntimeVersion = (projectDir) => {
}
}

const getWebpackConfig = (projectDir, env, configPath = "webpack.config.js") => {
const configAbsolutePath = path.resolve(projectDir, configPath);
let config;
try {
config = require(configAbsolutePath);
} catch (e) {
throw new Error(
`Couldn't load webpack config from ${configAbsolutePath}. ` +
`Original error:${EOL}${e}`
);
}
if (typeof config === "function") {
config = config(env);
}

if (!config) {
throw new Error(`Webpack config from ${configAbsolutePath} is empty!`);
}

return config;
};

const getPackageJson = projectDir => {
const packageJsonPath = getPackageJsonPath(projectDir);
return JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
Expand All @@ -53,7 +76,7 @@ const writePackageJson = (content, projectDir) => {
const packageJsonPath = getPackageJsonPath(projectDir);
fs.writeFileSync(packageJsonPath, JSON.stringify(content, null, 2))
}
const getProjectDir = ({ nestingLvl } = { nestingLvl: 0 }) => {
const getProjectDir = ({ nestingLvl } = { nestingLvl: 2 }) => {
// INIT_CWD is available since npm 5.4
const initCwd = process.env.INIT_CWD;
const shouldUseInitCwd = (() => {
Expand Down Expand Up @@ -115,14 +138,15 @@ const resolveAndroidConfigurationsPath = projectDir => {
const getPackageJsonPath = projectDir => path.resolve(projectDir, "package.json");

module.exports = {
isTypeScript,
isAngular,
isSass,
writePackageJson,
getAndroidProjectPath,
getAndroidRuntimeVersion,
getPackageJson,
getProjectDir,
getAndroidRuntimeVersion,
getAndroidProjectPath,
getWebpackConfig,
isAngular,
isSass,
isTypeScript,
resolveAndroidAppPath,
resolveAndroidConfigurationsPath,
writePackageJson,
};
8 changes: 4 additions & 4 deletions snapshot/android/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { chmodSync, createWriteStream, existsSync } = require("fs");
const { tmpdir } = require("os");
const { tmpdir, EOL } = require("os");
const { dirname, join } = require("path");

const { mkdir } = require("shelljs");
Expand Down Expand Up @@ -36,14 +36,14 @@ const getJsonFile = url =>
}

if (!response || response.statusCode !== 200) {
return reject(`Couldn't fetch ${url}! Response:\n${response}`);
return reject(`Couldn't fetch ${url}! Response:${EOL}${response}`);
}

try {
const data = JSON.parse(body);
resolve(data);
} catch (error) {
reject(`Couldn't parse json data! Original error:\n${error}`);
reject(`Couldn't parse json data! Original error:${EOL}${error}`);
}
})
).catch(reject);
Expand All @@ -58,7 +58,7 @@ const getRequestOptions = (url) =>
resolve(allOptions);
})
.catch(error =>
reject(`Couldn't get proxy settings! Original error:\n${error}`));
reject(`Couldn't get proxy settings! Original error:${EOL}${error}`));
});

module.exports = {
Expand Down
4 changes: 2 additions & 2 deletions templates/webpack.angular.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ module.exports = env => {
const ngToolsWebpackOptions = { tsConfigPath: "tsconfig.json" };

const config = {
context: resolve("./app"),
context: resolve(__dirname, "app"),
watchOptions: {
ignored: [
resolve("./app/App_Resources"),
resolve(__dirname, "./app/App_Resources"),
// Don't watch hidden files
"**/.*",
]
Expand Down
4 changes: 2 additions & 2 deletions templates/webpack.javascript.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ module.exports = env => {
const { snapshot, uglify, report } = env;

const config = {
context: resolve("./app"),
context: resolve(__dirname, "app"),
watchOptions: {
ignored: [
resolve("./app/App_Resources"),
resolve(__dirname, "./app/App_Resources"),
// Don't watch hidden files
"**/.*",
]
Expand Down
4 changes: 2 additions & 2 deletions templates/webpack.typescript.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ module.exports = env => {
const { snapshot, uglify, report } = env;

const config = {
context: resolve("./app"),
context: resolve(__dirname, "app"),
watchOptions: {
ignored: [
resolve("./app/App_Resources"),
resolve(__dirname, "./app/App_Resources"),
// Don't watch hidden files
"**/.*",
]
Expand Down
2 changes: 1 addition & 1 deletion verify/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const { forceUpdateProjectFiles } = require("../projectFilesManager");
const { forceUpdateProjectDeps } = require("../dependencyManager");

const PLUGIN_NAME = "nativescript-dev-webpack";
const PROJECT_DIR = getProjectDir({ nestingLvl: 2 });
const PROJECT_DIR = getProjectDir();

function update({
deps: shouldUpdateDeps,
Expand Down