diff --git a/packages/commonjs/src/utils.js b/packages/commonjs/src/utils.js index b9f3e17fb..e226a28fb 100644 --- a/packages/commonjs/src/utils.js +++ b/packages/commonjs/src/utils.js @@ -1,6 +1,6 @@ /* eslint-disable import/prefer-default-export */ -import { basename, dirname, extname, sep } from 'path'; +import { basename, dirname, extname } from 'path'; import { makeLegalIdentifier } from '@rollup/pluginutils'; @@ -27,8 +27,7 @@ export function getName(id) { if (name !== 'index') { return name; } - const segments = dirname(id).split(sep); - return makeLegalIdentifier(segments[segments.length - 1]); + return makeLegalIdentifier(basename(dirname(id))); } export function normalizePathSlashes(path) { diff --git a/packages/commonjs/test/fixtures/samples/module-path-separator/foo/index.js b/packages/commonjs/test/fixtures/samples/module-path-separator/foo/index.js new file mode 100644 index 000000000..fe9d6c941 --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/module-path-separator/foo/index.js @@ -0,0 +1 @@ +module.exports.a = 1; diff --git a/packages/commonjs/test/fixtures/samples/module-path-separator/main.js b/packages/commonjs/test/fixtures/samples/module-path-separator/main.js new file mode 100644 index 000000000..e965dbe8d --- /dev/null +++ b/packages/commonjs/test/fixtures/samples/module-path-separator/main.js @@ -0,0 +1,2 @@ +const foo = require("./foo"); +console.log(foo.a); diff --git a/packages/commonjs/test/test.js b/packages/commonjs/test/test.js index 2c7895801..8571f96ca 100644 --- a/packages/commonjs/test/test.js +++ b/packages/commonjs/test/test.js @@ -1,5 +1,6 @@ /* eslint-disable line-comment-position, no-new-func, no-undefined */ import * as path from 'path'; +import os from 'os'; import resolve from '@rollup/plugin-node-resolve'; @@ -728,3 +729,31 @@ test('does not affect subsequently created instances when called with `requireRe t.is(code1, code2); }); + +// This test works only on Windows, which treats both forward and backward +// slashes as path separators +if (os.platform() === 'win32') { + test('supports both forward and backward slash as path separator in directory-based modules', async (t) => { + const bundle = await rollup({ + input: 'fixtures/samples/module-path-separator/main.js', + plugins: [ + // Ad-hoc plugin that reverses the path separator of foo/index.js + { + name: 'test-path-separator-reverser', + async resolveId(source, importer) { + if (source.endsWith('foo')) { + const fullPath = path.resolve(path.dirname(importer), source, 'index.js'); + // Ensure that the module ID uses a non-default path separator + return fullPath.replace(/[\\/]/g, (sep) => (sep === '/' ? '\\' : '/')); + } + return null; + } + }, + commonjs() + ] + }); + + const code = await getCodeFromBundle(bundle); + t.regex(code, /\bfoo = {}/); + }); +}