Skip to content

Commit

Permalink
Make jsesc isScriptContext optional
Browse files Browse the repository at this point in the history
+ Adds option isScriptContext to constant folding plugin
+ Fix #440, fix #413
+ Related #384, #382
  • Loading branch information
boopathi committed Apr 3, 2017
1 parent f2e57e1 commit bdfbcfe
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
Expand Up @@ -3,9 +3,9 @@ jest.autoMockOff();
const babel = require("babel-core");
const unpad = require("../../../utils/unpad");

function transform(code) {
function transform(code, opts = {}) {
return babel.transform(code, {
plugins: [require("../src/index")]
plugins: [[require("../src/index"), opts]]
}).code;
}

Expand Down Expand Up @@ -83,7 +83,7 @@ describe("constant-folding-plugin", () => {
"<\\\\/script";
`
);
expect(transform(source)).toBe(expected);
expect(transform(source, { isScriptContext: true })).toBe(expected);
});

it("should handle style escape", () => {
Expand All @@ -98,7 +98,7 @@ describe("constant-folding-plugin", () => {
"<\\\\/style";
`
);
expect(transform(source)).toBe(expected);
expect(transform(source, { isScriptContext: true })).toBe(expected);
});

it("should handle html comment escape", () => {
Expand All @@ -113,6 +113,20 @@ describe("constant-folding-plugin", () => {
"\\\\x3C!--";
`
);
expect(transform(source, { isScriptContext: true })).toBe(expected);
});

it("should fix #440", () => {
const source = unpad(
`
var x = "'cool'" + "test";
`
);
const expected = unpad(
`
var x = "'cool'test";
`
);
expect(transform(source)).toBe(expected);
});
});
8 changes: 3 additions & 5 deletions packages/babel-plugin-minify-constant-folding/src/index.js
Expand Up @@ -55,7 +55,7 @@ module.exports = ({ types: t, traverse }) => {
},

// TODO: look into evaluating binding too (could result in more code, but gzip?)
Expression(path) {
Expression(path, { opts: { isScriptContext = false } }) {
const { node } = path;

if (node[seen]) {
Expand Down Expand Up @@ -122,10 +122,8 @@ module.exports = ({ types: t, traverse }) => {
}

// https://github.com/babel/babili/issues/382
if (typeof res.value === "string") {
res.value = jsesc(res.value, {
isScriptContext: true
});
if (typeof res.value === "string" && isScriptContext) {
res.value = jsesc(res.value, { isScriptContext });
}

const node = t.valueToNode(res.value);
Expand Down

0 comments on commit bdfbcfe

Please sign in to comment.