From fcd9826c9428e4f0a510eee14da0f94f2c66dc4e Mon Sep 17 00:00:00 2001 From: Brian Terlson Date: Mon, 26 Aug 2019 23:25:15 -0700 Subject: [PATCH] Normalize ids before looking up in named export map (#406) * Normalize ids before looking up in named export map * Fix path normalization tests on linux * clarify normalization comments --- src/index.js | 10 ++++++++-- test/test.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index 8da0742..dd9e74c 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,5 @@ import { realpathSync, existsSync } from 'fs'; -import { extname, resolve } from 'path'; +import { extname, resolve, normalize } from 'path'; import { sync as nodeResolveSync, isCore } from 'resolve'; import { createFilter } from 'rollup-pluginutils'; import { peerDependencies } from '../package.json'; @@ -40,6 +40,10 @@ export default function commonjs(options = {}) { } catch (err) { resolvedId = resolve(id); } + + // Note: customNamedExport's keys must be normalized file paths. + // resolve and nodeResolveSync both return normalized file paths + // so no additional normalization is necessary. customNamedExports[resolvedId] = options.namedExports[id]; if (existsSync(resolvedId)) { @@ -81,6 +85,8 @@ export default function commonjs(options = {}) { return null; } + const normalizedId = normalize(id); + const transformed = transformCommonjs( this.parse, code, @@ -88,7 +94,7 @@ export default function commonjs(options = {}) { this.getModuleInfo(id).isEntry, ignoreGlobal, ignoreRequire, - customNamedExports[id], + customNamedExports[normalizedId], sourceMap, allowDynamicRequire, ast diff --git a/test/test.js b/test/test.js index 8927c6f..c1787c8 100644 --- a/test/test.js +++ b/test/test.js @@ -822,5 +822,39 @@ exports.shuffleArray = shuffleArray_1; ` ); }); + + it('normalizes paths used in the named export map', async () => { + // Deliberately denormalizes file paths and ensures named exports + // continue to work. + function hookedResolve() { + const resolvePlugin = resolve(); + const oldResolve = resolvePlugin.resolveId; + resolvePlugin.resolveId = async function() { + const result = await oldResolve.apply(resolvePlugin, arguments); + if (result) { + result.id = result.id.replace(/\/|\\/, path.sep); + } + + return result; + }; + + return resolvePlugin; + } + + const bundle = await rollup({ + input: 'samples/custom-named-exports/main.js', + plugins: [ + hookedResolve(), + commonjs({ + namedExports: { + 'samples/custom-named-exports/secret-named-exporter.js': ['named'], + external: ['message'] + } + }) + ] + }); + + await executeBundle(bundle); + }); }); });