Skip to content

Instantly share code, notes, and snippets.

@janicduplessis
Created April 7, 2019 22:49
Show Gist options
  • Save janicduplessis/b8423f28977d80c1feda437756054627 to your computer and use it in GitHub Desktop.
Save janicduplessis/b8423f28977d80c1feda437756054627 to your computer and use it in GitHub Desktop.
const path = require('path');
const glob = require('glob');
const fs = require('fs');
const loadMetroConfig = require('@react-native-community/cli/build/tools/loadMetroConfig')
.default;
const loadConfig = require('@react-native-community/cli/build/tools/getLegacyConfig')
.default;
const Server = require('metro/src/Server');
const PROJECT_ROOT = path.join(__dirname, '../../../');
const CONFIG_FILE = path.join(__dirname, '../metro.config.js');
const ENTRY_FILE = path.join(__dirname, '../index.js');
const SOURCE_DIR = path.join(__dirname, '../src');
const DRY_RUN = false;
const PLATFORMS = ['ios', 'android'];
const globAsync = (pattern, options) =>
new Promise((resolve, reject) =>
glob(pattern, options, (err, res) => {
if (err != null) {
reject(err);
} else {
resolve(res);
}
})
);
const addAssets = async (config, bundledAssetsSet, platform, dev) => {
const server = new Server(config);
console.log('start processing assets', { platform, dev });
try {
const bundledAssets = await server.getAssets({
...Server.DEFAULT_BUNDLE_OPTIONS,
entryFile: ENTRY_FILE,
dev,
minify: false,
platform,
});
for (const asset of bundledAssets) {
for (const file of asset.files) {
bundledAssetsSet.add(file);
}
}
} finally {
server.end();
}
console.log('finished processing assets', { platform, dev });
};
async function cleanupAssets() {
const ctx = {
...loadConfig(),
reactNativePath: path.join(PROJECT_ROOT, 'node_modules/react-native'),
root: PROJECT_ROOT,
};
const config = await loadMetroConfig(ctx, {
resetCache: true,
config: CONFIG_FILE,
});
const bundledAssetsSet = new Set();
for (const p of PLATFORMS) {
await addAssets(config, bundledAssetsSet, p, false);
await addAssets(config, bundledAssetsSet, p, true);
}
const allAssets = await globAsync(
`**/*.@(${config.resolver.assetExts.join('|')})`,
{
cwd: SOURCE_DIR,
absolute: true,
}
);
for (const asset of allAssets) {
if (!bundledAssetsSet.has(asset)) {
if (DRY_RUN) {
console.log(asset);
} else {
fs.unlinkSync(asset);
}
}
}
}
cleanupAssets();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment