Skip to content

Add: constBindings option #48

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

Merged
merged 3 commits into from
Aug 11, 2024
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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ const plugin = createPlugin(
{
include?: Array,
exclude?: Array,
dynamicWrapper?: Function
dynamicWrapper?: Function,
constBindings?: Boolean
} = {}
);
```
Expand Down Expand Up @@ -119,6 +120,8 @@ const dynamicWrapper = (id) => {

Virtual modules are always transformed.

`constBindings` is a boolean. If true, the plugin will use `const` instead of `var` to declare the variable. This usually happens when you try to re-export the global variable. Default is false.

Changelog
---------

Expand Down
5 changes: 5 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ export type ExternalGlobalsOptions = {
* [dynamicWrapper] is used to specify dynamic imports. It accepts a variable name and returns an expression
*/
dynamicWrapper?: (variableName: VariableName) => string;

/**
* [constBindings] is used to decide whether to use `const` to declare variables. Default is `false`
*/
constBindings?: boolean;
};

export declare function externalGlobals(
Expand Down
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function isVirtualModule(id) {
return id.startsWith("\0");
}

function createPlugin(globals, {include, exclude, dynamicWrapper = defaultDynamicWrapper} = {}) {
function createPlugin(globals, {include, exclude, dynamicWrapper = defaultDynamicWrapper, constBindings = false} = {}) {
if (!globals) {
throw new TypeError("Missing mandatory option 'globals'");
}
Expand Down Expand Up @@ -70,7 +70,8 @@ function createPlugin(globals, {include, exclude, dynamicWrapper = defaultDynami
ast,
code,
getName,
getDynamicWrapper: dynamicWrapper
getDynamicWrapper: dynamicWrapper,
constBindings
});
return isTouched ? {
code: code.toString(),
Expand Down
14 changes: 7 additions & 7 deletions lib/import-to-globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ function makeGlobalName(prop, name) {
return `${name}.${prop}`;
}

function writeSpecLocal(code, root, spec, name, tempNames) {
function writeSpecLocal(code, root, spec, name, tempNames, constBindings) {
if (spec.isOverwritten) return;
// we always need an extra assignment for named export statement
// https://github.com/eight04/rollup-plugin-external-globals/issues/19
const localName = `_global_${makeLegalIdentifier(name)}`;
if (!tempNames.has(localName)) {
code.appendRight(root.start, `const ${localName} = ${name};\n`);
code.appendRight(root.start, `${constBindings ? "const" : "var"} ${localName} = ${name};\n`);
tempNames.add(localName);
}
if (spec.local.name === localName) {
Expand Down Expand Up @@ -72,7 +72,7 @@ function writeIdentifier(code, node, parent, name) {
}
}

function analyzeExportNamed(node, code, getName, tempNames) {
function analyzeExportNamed(node, code, getName, tempNames, constBindings) {
if (node.declaration || !node.source || !node.source.value) {
return false;
}
Expand All @@ -82,7 +82,7 @@ function analyzeExportNamed(node, code, getName, tempNames) {
}
for (const spec of node.specifiers) {
const globalName = makeGlobalName(spec.local.name, name);
writeSpecLocal(code, node, spec, globalName, tempNames);
writeSpecLocal(code, node, spec, globalName, tempNames, constBindings);
}
if (node.specifiers.length) {
code.overwrite(node.specifiers[node.specifiers.length - 1].end, node.source.end, "}");
Expand Down Expand Up @@ -126,7 +126,7 @@ class ExportLeftHand {
}
}

async function importToGlobals({ast, code, getName, getDynamicWrapper}) {
async function importToGlobals({ast, code, getName, getDynamicWrapper, constBindings}) {
await prepare();
let scope = attachScopes(ast, "scope");
const bindings = new Map;
Expand All @@ -139,7 +139,7 @@ async function importToGlobals({ast, code, getName, getDynamicWrapper}) {
if (node.type === "ImportDeclaration") {
isTouched = analyzeImport(node, bindings, code, getName, globals) || isTouched;
} else if (node.type === "ExportNamedDeclaration") {
isTouched = analyzeExportNamed(node, code, getName, tempNames) || isTouched;
isTouched = analyzeExportNamed(node, code, getName, tempNames, constBindings) || isTouched;
}
}

Expand All @@ -160,7 +160,7 @@ async function importToGlobals({ast, code, getName, getDynamicWrapper}) {
if (isReference(node, parent)) {
if (bindings.has(node.name) && !scope.contains(node.name)) {
if (parent.type === "ExportSpecifier") {
writeSpecLocal(code, topStatement, parent, bindings.get(node.name), tempNames);
writeSpecLocal(code, topStatement, parent, bindings.get(node.name), tempNames, constBindings);
} else {
writeIdentifier(code, node, parent, bindings.get(node.name));
}
Expand Down
37 changes: 31 additions & 6 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@
"author": "eight04 <eight04@gmail.com>",
"license": "MIT",
"devDependencies": {
"@eslint/js": "^9.9.0",
"@rollup/plugin-commonjs": "^26.0.1",
"c8": "^10.1.2",
"endent": "^2.1.0",
"eslint": "^9.5.0",
"globals": "^15.9.0",
"mocha": "^10.5.2",
"rollup": "^4.18.0",
"tempdir-yaml": "^0.3.0"
Expand Down
36 changes: 26 additions & 10 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,8 +309,8 @@ describe("main", () => {
mud: "MUD"
});
assert.equal(code.trim(), endent`
const _global_FOO_foo = FOO.foo;
const _global_MUD_mud = MUD.mud;
var _global_FOO_foo = FOO.foo;
var _global_MUD_mud = MUD.mud;

export { _global_FOO_foo as bar, _global_MUD_mud as mud };
`);
Expand All @@ -327,7 +327,7 @@ describe("main", () => {
foo: "FOO"
});
assert.equal(code.trim(), endent`
const _global_FOO_foo = FOO.foo;
var _global_FOO_foo = FOO.foo;

export { _global_FOO_foo as bar, _global_FOO_foo as baz };
`);
Expand All @@ -346,8 +346,8 @@ describe("main", () => {
boo: "BOO",
});
assert.equal(code.trim(), endent`
const _global_BAK = BAK;
const _global_BOO = BOO;
var _global_BAK = BAK;
var _global_BOO = BOO;

export { _global_BOO as BOO, _global_BAK as baz };
`);
Expand Down Expand Up @@ -383,6 +383,22 @@ describe("main", () => {
export {foo};
`, async resolve => {
const {output: {"entry.js": {code}}} = await bundle(resolve("entry.js"), {foo: "FOO"});
assert.equal(code.trim(), endent`
var _global_FOO = FOO;

export { _global_FOO as foo };
`);
})
);

it("constBindings", () =>
withDir(`
- entry.js: |
import foo from "foo";

export {foo};
`, async resolve => {
const {output: {"entry.js": {code}}} = await bundle(resolve("entry.js"), {foo: "FOO"}, undefined, {constBindings: true});
assert.equal(code.trim(), endent`
const _global_FOO = FOO;

Expand All @@ -401,7 +417,7 @@ describe("main", () => {
`, async resolve => {
const {output: {"entry.js": {code}}} = await bundle(resolve("entry.js"), {foo: "FOO"});
assert.equal(code.trim(), endent`
const _global_FOO = FOO;
var _global_FOO = FOO;

export { _global_FOO as bar, _global_FOO as foo };
`);
Expand All @@ -418,7 +434,7 @@ describe("main", () => {
const {output: {"entry.js": {code}}} = await bundle(resolve("entry.js"), {foo: "FOO"});
assert.equal(code.trim(), endent`
console.log(FOO);
const _global_FOO = FOO;
var _global_FOO = FOO;

export { _global_FOO as foo };
`);
Expand Down Expand Up @@ -521,7 +537,7 @@ describe("main", () => {
}
);
assert.equal(code.trim(), endent`
const _global_BAR = BAR;
var _global_BAR = BAR;

const bar = _global_BAR;
console.log('foo');
Expand Down Expand Up @@ -563,7 +579,7 @@ describe("main", () => {
assert.equal(code.trim(), endent`
var entry = {};

const _global_BAR = BAR;
var _global_BAR = BAR;

const { a } = _global_BAR;
console.log(a);
Expand Down Expand Up @@ -609,7 +625,7 @@ describe("main", () => {
}
);
assert.equal(code.trim(), endent`
const _global_BAR = BAR;
var _global_BAR = BAR;

var foo = (val) => {
const { a } = _global_BAR;
Expand Down
Loading