UNPKG

1.62 kBJavaScriptView Raw
1import { dirname, isAbsolute, resolve } from 'path';
2import { readFileSync } from 'sander';
3
4export function defaultResolver ( importee, importer, options ) {
5 // absolute paths are left untouched
6 if ( isAbsolute( importee ) ) return importee;
7
8 // we try to resolve external modules
9 if ( importee[0] !== '.' ) {
10 // unless we want to keep it external, that is
11 if ( ~options.external.indexOf( importee ) ) return null;
12
13 return options.resolveExternal( importee, importer, options );
14 }
15
16 return resolve( dirname( importer ), importee ).replace( /\.js$/, '' ) + '.js';
17}
18
19export function defaultExternalResolver ( id, importer, options ) {
20 // for now, only node_modules is supported, and only jsnext:main
21 let dir = dirname( importer );
22
23 while ( dir !== '/' ) {
24 const pkgPath = resolve( dir, 'node_modules', id, 'package.json' );
25 let pkgJson;
26
27 try {
28 pkgJson = readFileSync( pkgPath ).toString();
29 } catch ( err ) {
30 // noop
31 }
32
33 if ( pkgJson ) {
34 let pkg;
35
36 try {
37 pkg = JSON.parse( pkgJson );
38 } catch ( err ) {
39 throw new Error( `Malformed JSON: ${pkgPath}` );
40 }
41
42 const main = pkg[ 'jsnext:main' ];
43
44 if ( !main ) {
45 throw new Error( `Package ${id} does not have a jsnext:main field, and so cannot be included in your rollup. Try adding it as an external module instead (e.g. options.external = ['${id}']). See https://github.com/rollup/rollup/wiki/jsnext:main for more info` );
46 }
47
48 return resolve( dirname( pkgPath ), main ).replace( /\.js$/, '' ) + '.js';
49 }
50
51 dir = dirname( dir );
52 }
53
54 throw new Error( `Could not find package ${id} (required by ${importer})` );
55}