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

feat(commonjs): set syntheticNamedExports for commonjs modules #149

Merged
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
41 changes: 0 additions & 41 deletions packages/commonjs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,47 +106,6 @@ Default: `true`

If false, skips source map generation for CommonJS modules.

### `namedExports`

Type: `Object`<br>
Default: `null`

Explicitly specify unresolvable named exports.

This plugin will attempt to create named exports, where appropriate, so you can do this...

```js
// importer.js
import { named } from './exporter.js';

// exporter.js
module.exports = { named: 42 }; // or `exports.named = 42;`
```

...but that's not always possible:

```js
// importer.js
import { named } from 'my-lib';

// my-lib.js
var myLib = exports;
myLib.named = "you can't see me";
```

In those cases, you can specify custom named exports:

```js
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'my-lib': ['named']
}
});
```

### `ignore`

Type: `Array[...String | (String) => Boolean]`<br>
Expand Down
4 changes: 2 additions & 2 deletions packages/commonjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"require"
],
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0"
"rollup": "^2.3.4"
},
"dependencies": {
"@rollup/pluginutils": "^3.0.8",
Expand All @@ -67,7 +67,7 @@
"locate-character": "^2.0.5",
"prettier": "^1.19.1",
"require-relative": "^0.8.7",
"rollup": "^2.0.0",
"rollup": "^2.3.4",
"rollup-plugin-babel": "^4.3.3",
"shx": "^0.3.2",
"source-map": "^0.6.1",
Expand Down
48 changes: 8 additions & 40 deletions packages/commonjs/src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { realpathSync, existsSync, readFileSync } from 'fs';
import { extname, resolve, normalize, join } from 'path';
import { existsSync, readFileSync } from 'fs';
import { extname, join } from 'path';

import { sync as nodeResolveSync, isCore } from 'resolve';
import { createFilter } from '@rollup/pluginutils';

import getCommonDir from 'commondir';
Expand Down Expand Up @@ -48,40 +47,6 @@ export default function commonjs(options = {}) {
? getCommonDir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
: null;

const customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach((id) => {
let resolveId = id;
let resolvedId;

if (isCore(id)) {
// resolve will not find npm modules with the same name as
// core modules without a trailing slash. Since core modules
// must be external, we can assume any core modules defined
// here are npm modules by that name.
resolveId += '/';
}

try {
resolvedId = nodeResolveSync(resolveId, { basedir: process.cwd() });
} 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)) {
const realpath = realpathSync(resolvedId);
if (realpath !== resolvedId) {
customNamedExports[realpath] = options.namedExports[id];
}
}
});
}

const esModulesWithoutDefaultExport = new Set();
const esModulesWithDefaultExport = new Set();

Expand Down Expand Up @@ -111,8 +76,6 @@ export default function commonjs(options = {}) {
return null;
}

const normalizedId = normalize(id);

const transformed = transformCommonjs(
this.parse,
code,
Expand All @@ -121,7 +84,6 @@ export default function commonjs(options = {}) {
isEsModule,
ignoreGlobal || isEsModule,
ignoreRequire,
customNamedExports[normalizedId],
sourceMap,
isDynamicRequireModulesEnabled,
dynamicRequireModuleSet,
Expand All @@ -143,6 +105,12 @@ export default function commonjs(options = {}) {
name: 'commonjs',

buildStart() {
if (options.namedExports != null) {
this.warn(
'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
);
}

const [major, minor] = this.meta.rollupVersion.split('.').map(Number);
const minVersion = peerDependencies.rollup.slice(2);
const [minMajor, minMinor] = minVersion.split('.').map(Number);
Expand Down
8 changes: 3 additions & 5 deletions packages/commonjs/src/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ export function transformCommonjs(
isEsModule,
ignoreGlobal,
ignoreRequire,
customNamedExports,
sourceMap,
isDynamicRequireModulesEnabled,
dynamicRequireModuleSet,
Expand Down Expand Up @@ -562,8 +561,6 @@ export function transformCommonjs(
});
}

if (customNamedExports) customNamedExports.forEach(addExport);

const defaultExportPropertyAssignments = [];
let hasDefaultExport = false;

Expand Down Expand Up @@ -648,12 +645,13 @@ export function transformCommonjs(
.trim()
.append(wrapperEnd);

if (hasDefaultExport || named.length > 0 || shouldWrap || (!isEntry && !isEsModule)) {
const injectExportBlock = hasDefaultExport || named.length > 0 || shouldWrap || !isEntry;
if (injectExportBlock) {
magicString.append(exportBlock);
}

code = magicString.toString();
const map = sourceMap ? magicString.generateMap() : null;

return { code, map };
return { code, map, syntheticNamedExports: injectExportBlock };
}
1 change: 1 addition & 0 deletions packages/commonjs/test/fixtures/.eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"func-names": "off",
"no-console": "off",
"no-undefined": "off",
"no-undef": "off",
"import/prefer-default-export": "off",
"import/extensions": "off",
"import/no-unresolved": "off",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@ import * as x from './answer';

t.truthy('answer' in x);
t.truthy('default' in x);
t.truthy(!('__esModule' in x));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this change, __esModule is available as a named import. In my opinion this is correct, since it's exported from the commonjs module. What do you think?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lukastaegert this is something you'd have to approve. not speaking for the other maintainers, but I lack the knowledge to know if this is a good change.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually the list of exports is detected via Object.keys which would skip the __esModule property since it is defined to be non-enumerable. I would be interested in how this list is being gathered that it is including it.

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { named } from './x.js';

t.is(named, 'foo');
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
if (typeof someUnknownGlobal !== 'undefined') {
module.exports = { named: 'bar' };
} else {
module.exports = { named: 'foo' };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
context: {
window: {}
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { named } from './x.js';

t.is(named, undefined);

window.addExport('named', 'foo');

t.is(named, 'foo');
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
window.addExport = (key, value) => {
module.exports[key] = value;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { named } from './x.js';

t.is(named, 'foo');
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Object.defineProperty(module.exports, 'named', {
enumerable: true,
get: function get() {
return 'foo';
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.named = 2;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { named } from './reexport.js';

t.is(named, 2);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const myModule = require('./export.js');

module.exports.named = myModule.named;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { nonExisting } from './x.js';

t.is(nonExisting, undefined);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.named = 2;

This file was deleted.

This file was deleted.

This file was deleted.

3 changes: 0 additions & 3 deletions packages/commonjs/test/fixtures/function/reexports/main.js

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading