Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(assets): Explicit mode allows all non-JS file extensions #85

Merged
merged 5 commits into from
Aug 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
node_modules
web_modules
pkg

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 37 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import rimraf from 'rimraf';
import chalk from 'chalk';
import ora from 'ora';
import yargs from 'yargs-parser';
import { sync as mkdirSync } from 'mkdirp';

import * as rollup from 'rollup';
import rollupPluginNodeResolve from 'rollup-plugin-node-resolve';
Expand All @@ -21,6 +22,10 @@ function fromEntries(iterable: [string, string][]): {[key: string]: string} {
.reduce((obj, { 0: key, 1: val }) => Object.assign(obj, { [key]: val }), {})
}

export interface DependencyLoc {
depLoc?: string,
assetLoc?: string
}

export interface InstallOptions {
destLoc: string;
Expand Down Expand Up @@ -104,7 +109,7 @@ function detectExports(filePath: string): string[] | undefined {
* Follows logic similar to Node's resolution logic, but using a package.json's ESM "module"
* field instead of the CJS "main" field.
*/
function resolveWebDependency(dep: string, isExplicit: boolean, isOptimized: boolean): string {
function resolveWebDependency(dep: string, isExplicit: boolean, isOptimized: boolean): DependencyLoc {
const nodeModulesLoc = path.join(cwd, 'node_modules', dep);
let dependencyStats: fs.Stats;
try {
Expand All @@ -116,7 +121,14 @@ function resolveWebDependency(dep: string, isExplicit: boolean, isOptimized: boo
);
}
if (dependencyStats.isFile()) {
return nodeModulesLoc;
const locations: DependencyLoc = {};
const isJSFile = ['.js', '.mjs', '.cjs'].includes(path.extname(dep));
if (isJSFile) {
locations.depLoc = nodeModulesLoc;
} else {
locations.assetLoc = nodeModulesLoc;
}
return locations;
}
if (dependencyStats.isDirectory()) {
const dependencyManifestLoc = path.join(nodeModulesLoc, 'package.json');
Expand All @@ -138,7 +150,11 @@ function resolveWebDependency(dep: string, isExplicit: boolean, isOptimized: boo
chalk.italic(`See: ${chalk.underline('https://github.com/pikapkg/web#a-note-on-react')}`),
);
}
return path.join(nodeModulesLoc, foundEntrypoint);
const locations: DependencyLoc = {};
if (foundEntrypoint) {
locations.depLoc = path.join(nodeModulesLoc, foundEntrypoint);
}
return locations;
}

throw new Error(`Error loading "${dep}" at "${nodeModulesLoc}". (MODE=${dependencyStats.mode}) `);
Expand Down Expand Up @@ -175,16 +191,23 @@ export async function install(
rimraf.sync(destLoc);
}

const depObject = {};
const depObject: {[depName: string]: string} = {};
const assetObject: {[depName: string]: string} = {};
const importMap = {};
const skipFailures = !isExplicit;
for (const dep of arrayOfDeps) {
try {
const depName = getWebDependencyName(dep);
const depLoc = resolveWebDependency(dep, isExplicit, isOptimized);
depObject[depName] = depLoc;
importMap[depName] = `./${depName}.js`;
detectionResults.push([dep, true]);
const { depLoc, assetLoc } = resolveWebDependency(dep, isExplicit, isOptimized);
if (depLoc) {
depObject[depName] = depLoc;
importMap[depName] = `./${depName}.js`;
detectionResults.push([dep, true]);
}
if (assetLoc) {
assetObject[depName] = assetLoc;
detectionResults.push([dep, true]);
}
spinner.text = banner + formatDetectionResults(skipFailures);
} catch (err) {
detectionResults.push([dep, false]);
Expand All @@ -200,7 +223,7 @@ export async function install(
return false;
}
}
if (Object.keys(depObject).length === 0) {
if (Object.keys(depObject).length === 0 && Object.keys(assetObject).length === 0) {
logError(`No ESM dependencies found!`);
console.log(chalk.dim(` At least one dependency must have an ESM "module" entrypoint. You can find modern, web-ready packages at ${chalk.underline('https://www.pika.dev')}`));
return false;
Expand Down Expand Up @@ -278,6 +301,10 @@ export async function install(
};
const packageBundle = await rollup.rollup(inputOptions);
await packageBundle.write(outputOptions);
Object.entries(assetObject).forEach(([assetName, assetLoc]) => {
mkdirSync(`${destLoc}/${path.dirname(assetName)}`);
fs.copyFileSync(assetLoc, `${destLoc}/${assetName}`);
});
fs.writeFileSync(
path.join(destLoc, 'import-map.json'),
JSON.stringify({imports: importMap}, undefined, 2), {encoding: 'utf8'}
Expand Down Expand Up @@ -324,7 +351,7 @@ export async function cli(args: string[]) {
);
}
if (spinnerHasError) {
// Set the exit code so that programatic usage of the CLI knows that there were errors.
// Set the exit code so that programmatic usage of the CLI knows that there were errors.
spinner.warn(chalk(`Finished with warnings.`));
process.exitCode = 1;
}
Expand Down