From e1599fb59bb420c75c024b7a23d9ab0095e11da6 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Sun, 22 Apr 2018 22:33:08 +0200 Subject: [PATCH 01/14] implement compact output option --- src/Chunk.ts | 19 ++-- src/ast/nodes/Import.ts | 52 ++++++----- src/ast/variables/NamespaceVariable.ts | 28 +++--- src/finalisers/amd.ts | 21 +++-- src/finalisers/cjs.ts | 77 ++++++++++------ src/finalisers/esm.ts | 45 +++++---- src/finalisers/iife.ts | 38 ++++---- src/finalisers/shared/esModuleExport.ts | 3 +- src/finalisers/shared/getExportBlock.ts | 34 ++++--- src/finalisers/shared/getInteropBlock.ts | 9 +- src/finalisers/shared/setupNamespace.ts | 19 +++- src/finalisers/system.ts | 69 ++++++++------ src/finalisers/umd.ts | 91 +++++++++---------- src/rollup/types.d.ts | 1 + src/utils/mergeOptions.ts | 5 +- src/utils/renderHelpers.ts | 1 + test/form/samples/compact/_config.js | 9 ++ test/form/samples/compact/_expected/amd.js | 3 + test/form/samples/compact/_expected/cjs.js | 3 + test/form/samples/compact/_expected/es.js | 3 + test/form/samples/compact/_expected/iife.js | 3 + test/form/samples/compact/_expected/system.js | 3 + test/form/samples/compact/_expected/umd.js | 3 + test/form/samples/compact/main.js | 3 + .../samples/indent-false/_expected/umd.js | 6 +- test/misc/optionList.js | 4 +- 26 files changed, 325 insertions(+), 227 deletions(-) create mode 100644 test/form/samples/compact/_config.js create mode 100644 test/form/samples/compact/_expected/amd.js create mode 100644 test/form/samples/compact/_expected/cjs.js create mode 100644 test/form/samples/compact/_expected/es.js create mode 100644 test/form/samples/compact/_expected/iife.js create mode 100644 test/form/samples/compact/_expected/system.js create mode 100644 test/form/samples/compact/_expected/umd.js create mode 100644 test/form/samples/compact/main.js diff --git a/src/Chunk.ts b/src/Chunk.ts index b2f823f9142..5bb16e26147 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -726,13 +726,16 @@ export default class Chunk { preRender(options: OutputOptions, inputBase: string) { timeStart('render modules', 3); - let magicString = new MagicStringBundle({ separator: '\n\n' }); + let magicString = new MagicStringBundle({ separator: options.compact ? '' : '\n\n' }); this.usedModules = []; - this.indentString = getIndentString(this.orderedModules, options); + this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options); + + const nl = options.compact ? '' : '\n'; if (this.graph.dynamicImport) this.prepareDynamicImports(); const renderOptions: RenderOptions = { + compact: options.compact, legacy: options.legacy, freeze: options.freeze !== false, namespaceToStringTag: options.namespaceToStringTag === true, @@ -782,13 +785,13 @@ export default class Chunk { if (namespace.needsNamespaceBlock) { const rendered = namespace.renderBlock(renderOptions); - if (namespace.renderFirst()) hoistedSource += '\n' + rendered; + if (namespace.renderFirst()) hoistedSource += nl + rendered; else magicString.addSource(new MagicString(rendered)); } } } - if (hoistedSource) magicString.prepend(hoistedSource + '\n\n'); + if (hoistedSource) magicString.prepend(hoistedSource + nl + nl); this.renderedSource = magicString.trim(); this.renderedSourceLength = undefined; @@ -965,6 +968,8 @@ export default class Chunk { render(options: OutputOptions, addons: Addons) { timeStart('render format', 3); + const nl = options.compact ? '' : '\n'; + if (!this.renderedSource) throw new Error('Internal error: Chunk render called before preRender'); @@ -1020,8 +1025,8 @@ export default class Chunk { }, options ); - if (addons.banner) magicString.prepend(addons.banner + '\n'); - if (addons.footer) magicString.append('\n' + addons.footer); + if (addons.banner) magicString.prepend(addons.banner + nl); + if (addons.footer) magicString.append(nl + addons.footer); const prevCode = magicString.toString(); timeEnd('render format', 3); @@ -1060,7 +1065,7 @@ export default class Chunk { timeEnd('sourcemap', 3); } - if (code[code.length - 1] !== '\n') code += '\n'; + if (options.compact !== true && code[code.length - 1] !== '\n') code += '\n'; return { code, map }; } ); diff --git a/src/ast/nodes/Import.ts b/src/ast/nodes/Import.ts index ee02e2f6f9f..85a70a15688 100644 --- a/src/ast/nodes/Import.ts +++ b/src/ast/nodes/Import.ts @@ -11,26 +11,32 @@ interface DynamicImportMechanism { interopRight?: string; } -const dynamicImportMechanisms: Record = { - es: undefined, - cjs: { - left: 'Promise.resolve(require(', - right: '))', - interopLeft: 'Promise.resolve({ default: require(', - interopRight: ') })' - }, - amd: { - left: 'new Promise(function (resolve, reject) { require([', - right: '], resolve, reject) })', - interopLeft: 'new Promise(function (resolve, reject) { require([', - interopRight: '], function (m) { resolve({ default: m }) }, reject) })' - }, - system: { - left: 'module.import(', - right: ')' - }, - umd: undefined, - iife: undefined +const getDynamicImportMechanism = (format: string, compact: boolean): DynamicImportMechanism => { + switch (format) { + case 'cjs': { + const _ = compact ? '' : ' '; + return { + left: 'Promise.resolve(require(', + right: '))', + interopLeft: `Promise.resolve({${_}default:${_}require(`, + interopRight: `)${_}})` + }; + } + case 'amd': { + const _ = compact ? '' : ' '; + return { + left: `new Promise(function${_}(resolve,${_}reject)${_}{${_}require([`, + right: `],${_}resolve,${_}reject)${_}})`, + interopLeft: `new Promise(function${_}(resolve,${_}reject)${_}{${_}require([`, + interopRight: `],${_}function${_}(m)${_}{${_}resolve({${_}default:${_}m${_}})${_}},${_}reject)${_}})` + }; + } + case 'system': + return { + left: 'module.import(', + right: ')' + }; + } }; export default class Import extends NodeBase { @@ -58,15 +64,17 @@ export default class Import extends NodeBase { render(code: MagicString, options: RenderOptions) { this.rendered = true; if (this.resolutionNamespace) { + const _ = options.compact ? '' : ' '; + const s = options.compact ? '' : ';'; code.overwrite( this.parent.start, this.parent.end, - `Promise.resolve().then(function () { return ${this.resolutionNamespace}; })` + `Promise.resolve().then(function${_}()${_}{${_}return ${this.resolutionNamespace}${s}${_}})` ); return; } - const importMechanism = dynamicImportMechanisms[options.format]; + const importMechanism = getDynamicImportMechanism(options.format, options.compact); if (importMechanism) { const leftMechanism = (this.resolutionInterop && importMechanism.interopLeft) || importMechanism.left; diff --git a/src/ast/variables/NamespaceVariable.ts b/src/ast/variables/NamespaceVariable.ts index 3e0dafbd9a3..2f1e9139ed8 100644 --- a/src/ast/variables/NamespaceVariable.ts +++ b/src/ast/variables/NamespaceVariable.ts @@ -47,11 +47,14 @@ export default class NamespaceVariable extends Variable { } renderBlock(options: RenderOptions) { + const _ = options.compact ? '' : ' '; + const n = options.compact ? '' : '\n'; + const members = Object.keys(this.originals).map(name => { const original = this.originals[name]; if ((this.referencedEarly || original.isReassigned) && !options.legacy) { - return `${options.indent}get ${name} () { return ${original.getName()}; }`; + return `${options.indent}get ${name}${_}()${_}{${_}return${_}${original.getName()};${_}}`; } if (options.legacy && reservedWords.indexOf(name) !== -1) name = `'${name}'`; @@ -61,27 +64,28 @@ export default class NamespaceVariable extends Variable { const name = this.getName(); const callee = options.freeze - ? `/*#__PURE__*/${options.legacy ? `(Object.freeze || Object)` : `Object.freeze`}` + ? `${options.compact ? '' : '/*#__PURE__*/'}${ + options.legacy ? `(Object.freeze${_}||${_}Object)` : `Object.freeze` + }` : ''; let output = `${this.context.varOrConst} ${name} = ${ options.namespaceToStringTag - ? `{\n${members.join(',\n')}\n};` - : `${callee}({\n${members.join(',\n')}\n});` + ? `{${n}${members.join(`,${n}`)}${n}};` + : `${callee}({${n}${members.join(`,${n}`)}${n}});` }`; if (options.namespaceToStringTag) { - output += `\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag) -${options.indent}Object.defineProperty(${name}, Symbol.toStringTag, { value: 'Module' }); -else -${ - options.indent - }Object.defineProperty(${name}, 'toString', { value: function () { return '[object Module]' } }); -${callee}(${name});`; + const t = options.indent; + output += `${n}if${_}(typeof Symbol${_}!==${_}'undefined'${_}&&${_}Symbol.toStringTag)${n}`; + output += `${t}Object.defineProperty(${name},${_}Symbol.toStringTag,${_}{${_}value:${_}'Module'${_}});${n}`; + output += `else${n}`; + output += `${t}Object.defineProperty(${name},${_}'toString',${_}{${_}value:${_}function${_}()${_}{${_}return${_}'[object Module]'${_}}${_}});${n}`; + output += `${callee}(${name});`; } if (options.format === 'system' && this.exportName) { - output += `\nexports('${this.exportName}', ${name});`; + output += `${n}exports('${this.exportName}',${_}${name});`; } return output; diff --git a/src/finalisers/amd.ts b/src/finalisers/amd.ts index e3e184f3a32..33b565c0ea7 100644 --- a/src/finalisers/amd.ts +++ b/src/finalisers/amd.ts @@ -1,6 +1,6 @@ import getInteropBlock from './shared/getInteropBlock'; import getExportBlock from './shared/getExportBlock'; -import esModuleExport from './shared/esModuleExport'; +import { esModuleExport, compactEsModuleExport } from './shared/esModuleExport'; import warnOnBuiltins from './shared/warnOnBuiltins'; import { Bundle as MagicStringBundle } from 'magic-string'; import { OutputOptions } from '../rollup/types'; @@ -27,6 +27,8 @@ export default function amd( const deps = dependencies.map(m => `'${m.id}'`); const args = dependencies.map(m => m.name); + const nl = options.compact ? '' : '\n'; + const _ = options.compact ? '' : ' '; if (namedExportsMode && hasExports) { args.unshift(`exports`); @@ -46,26 +48,29 @@ export default function amd( const amdOptions = options.amd || {}; const params = - (amdOptions.id ? `'${amdOptions.id}', ` : ``) + (deps.length ? `[${deps.join(', ')}], ` : ``); + (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) + + (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``); - const useStrict = options.strict !== false ? ` 'use strict';` : ``; + const useStrict = options.strict !== false ? `${_}'use strict';` : ``; const define = amdOptions.define || 'define'; - const wrapperStart = `${define}(${params}function (${args.join(', ')}) {${useStrict}\n\n`; + const wrapperStart = `${define}(${params}function${_}(${args.join( + `,${_}` + )})${_}{${useStrict}${nl}${nl}`; // var foo__default = 'default' in foo ? foo['default'] : foo; const interopBlock = getInteropBlock(dependencies, options, graph.varOrConst); - if (interopBlock) magicString.prepend(interopBlock + '\n\n'); + if (interopBlock) magicString.prepend(interopBlock + nl + nl); if (intro) magicString.prepend(intro); const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop); - if (exportBlock) magicString.append('\n\n' + exportBlock); + if (exportBlock) magicString.append(nl + nl + exportBlock); if (namedExportsMode && hasExports && options.legacy !== true && isEntryModuleFacade) - magicString.append(`\n\n${esModuleExport}`); + magicString.append(`${nl}${nl}${options.compact ? compactEsModuleExport : esModuleExport}`); if (outro) magicString.append(outro); return magicString .indent(indentString) - .append('\n\n});') + .append(nl + nl + '});') .prepend(wrapperStart); } diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index a11072478a5..7f76fc70552 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -1,4 +1,4 @@ -import esModuleExport from './shared/esModuleExport'; +import { esModuleExport, compactEsModuleExport } from './shared/esModuleExport'; import { OutputOptions } from '../rollup/types'; import { Bundle as MagicStringBundle } from 'magic-string'; import getExportBlock from './shared/getExportBlock'; @@ -18,10 +18,13 @@ export default function cjs( }: FinaliserOptions, options: OutputOptions ) { + const nl = options.compact ? '' : '\n'; + const _ = options.compact ? '' : ' '; + intro = - (options.strict === false ? intro : `'use strict';\n\n${intro}`) + + (options.strict === false ? intro : `'use strict';${nl}${nl}${intro}`) + (namedExportsMode && hasExports && options.legacy !== true && isEntryModuleFacade - ? `${esModuleExport}\n\n` + ? `${esModuleExport}${nl}${nl}` : ''); let needsInterop = false; @@ -29,59 +32,75 @@ export default function cjs( const varOrConst = graph.varOrConst; const interop = options.interop !== false; - const importBlock = dependencies - .map( - ({ - id, - namedExportsMode, - isChunk, - name, - reexports, - imports, - exportsNames, - exportsDefault - }) => { + let importBlock: string; + + if (options.compact) { + let definingVariable = false; + importBlock = ''; + + dependencies.forEach( + ({ id, namedExportsMode, isChunk, name, reexports, imports, exportsNames, exportsDefault }) => { if (!reexports && !imports) { - return `require('${id}');`; + importBlock += definingVariable ? ';' : ','; + definingVariable = false; + importBlock += `require('${id}')`; + } else { + importBlock += definingVariable ? ',' : ';${varOrConst} '; + definingVariable = true; + + if (!interop || isChunk || !exportsDefault || !namedExportsMode) { + importBlock += `${name}=require('${id}')`; + } else { + needsInterop = true; + if (exportsNames) + importBlock += `${name}=require('${id}'),${name}__default=_interopDefault(${name})`; + else importBlock += `${name}=_interopDefault(require('${id}'))`; + } } + } + ); + } else { + importBlock = dependencies + .map(({ id, isChunk, name, reexports, imports, exportsNames, exportsDefault }) => { + if (!reexports && !imports) return `require('${id}');`; - if (!interop || isChunk || !exportsDefault || !namedExportsMode) { + if (!interop || isChunk || !exportsDefault || !namedExportsMode) return `${varOrConst} ${name} = require('${id}');`; - } needsInterop = true; - if (exportsNames) { + if (exportsNames) return ( `${varOrConst} ${name} = require('${id}');` + `\n${varOrConst} ${name}__default = _interopDefault(${name});` ); - } return `${varOrConst} ${name} = _interopDefault(require('${id}'));`; - } - ) - .join('\n'); + }) + .join('\n'); + } if (needsInterop) { - intro += `function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\n`; + if (options.compact) + intro += `function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}`; + else + intro += `function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\n`; } - if (importBlock) { - intro += importBlock + '\n\n'; - } + if (importBlock) intro += importBlock + nl + nl; const exportBlock = getExportBlock( exports, dependencies, namedExportsMode, options.interop, - 'module.exports =' + options.compact, + `module.exports${_}=` ); magicString.prepend(intro); - if (exportBlock) magicString.append('\n\n' + exportBlock); + if (exportBlock) magicString.append(nl + nl + exportBlock); if (outro) magicString.append(outro); return magicString; diff --git a/src/finalisers/esm.ts b/src/finalisers/esm.ts index 986a2d5a9f5..af2ce4a71a9 100644 --- a/src/finalisers/esm.ts +++ b/src/finalisers/esm.ts @@ -1,27 +1,34 @@ import { Bundle as MagicStringBundle } from 'magic-string'; import { FinaliserOptions } from './index'; +export * from 'magic-string'; +import { OutputOptions } from '../rollup/types'; + export default function esm( magicString: MagicStringBundle, - { intro, outro, dependencies, exports }: FinaliserOptions + { intro, outro, dependencies, exports }: FinaliserOptions, + options: OutputOptions ) { + const _ = options.compact ? '' : ' '; + const nl = options.compact ? '' : '\n'; + const importBlock = dependencies .map(({ id, reexports, imports, name }) => { if (!reexports && !imports) { - return `import '${id}';`; + return `import${_}'${id}';`; } let output = ''; if (imports) { const defaultImport = imports.find(specifier => specifier.imported === 'default'); const starImport = imports.find(specifier => specifier.imported === '*'); if (starImport) { - output += `import * as ${starImport.local} from '${id}';`; - if (imports.length > 1) output += '\n'; + output += `import${_}*${_}as ${starImport.local} from${_}'${id}';`; + if (imports.length > 1) output += nl; } if (defaultImport && imports.length === 1) { - output += `import ${defaultImport.local} from '${id}';`; + output += `import ${defaultImport.local} from${_}'${id}';`; } else if (!starImport || imports.length > 1) { - output += `import ${defaultImport ? `${defaultImport.local}, ` : ''}{ ${imports + output += `import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${imports .filter(specifier => specifier !== defaultImport && specifier !== starImport) .map(specifier => { if (specifier.imported === specifier.local) { @@ -30,29 +37,29 @@ export default function esm( return `${specifier.imported} as ${specifier.local}`; } }) - .join(', ')} } from '${id}';`; + .join(`,${_}`)}${_}}${_}from${_}'${id}';`; } } if (reexports) { - if (imports) output += '\n'; + if (imports) output += nl; const starExport = reexports.find(specifier => specifier.reexported === '*'); const namespaceReexport = reexports.find( specifier => specifier.imported === '*' && specifier.reexported !== '*' ); if (starExport) { - output += `export * from '${id}';`; + output += `export${_}*${_}from${_}'${id}';`; if (reexports.length === 1) { return output; } - output += '\n'; + output += nl; } if (namespaceReexport) { if ( !imports || !imports.some(specifier => specifier.imported === '*' && specifier.local === name) ) - output += `import * as ${name} from '${id}';\n`; - output += `export { ${ + output += `import${_}*${_}as ${name} from${_}'${id}';${nl}`; + output += `export${_}{${_}${ name === namespaceReexport.reexported ? name : `${name} as ${namespaceReexport.reexported}` @@ -60,9 +67,9 @@ export default function esm( if (reexports.length === (starExport ? 2 : 1)) { return output; } - output += '\n'; + output += nl; } - output += `export { ${reexports + output += `export${_}{${_}${reexports .filter(specifier => specifier !== starExport && specifier !== namespaceReexport) .map(specifier => { if (specifier.imported === specifier.reexported) { @@ -71,13 +78,13 @@ export default function esm( return `${specifier.imported} as ${specifier.reexported}`; } }) - .join(', ')} } from '${id}';`; + .join(`,${_}`)}${_}}${_}from${_}'${id}';`; } return output; }) - .join('\n'); + .join(nl); - if (importBlock) intro += importBlock + '\n\n'; + if (importBlock) intro += importBlock + nl + nl; if (intro) magicString.prepend(intro); const exportBlock: string[] = []; @@ -94,10 +101,10 @@ export default function esm( } }); if (exportDeclaration.length) { - exportBlock.push(`export { ${exportDeclaration.join(', ')} };`); + exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`); } - if (exportBlock.length) magicString.append('\n\n' + exportBlock.join('\n').trim()); + if (exportBlock.length) magicString.append(nl + nl + exportBlock.join(nl).trim()); if (outro) magicString.append(outro); diff --git a/src/finalisers/iife.ts b/src/finalisers/iife.ts index 9fd50464481..e58b6719f5d 100644 --- a/src/finalisers/iife.ts +++ b/src/finalisers/iife.ts @@ -14,18 +14,12 @@ const thisProp = (name: string) => `this${keypath(name)}`; export default function iife( magicString: MagicStringBundle, - { - graph, - namedExportsMode, - hasExports, - indentString, - intro, - outro, - dependencies, - exports - }: FinaliserOptions, + { graph, namedExportsMode, hasExports, indentString: t, intro, outro, dependencies, exports }: FinaliserOptions, options: OutputOptions ) { + const _ = options.compact ? '' : ' '; + const nl = options.compact ? '' : '\n'; + const { extend, name } = options; const isNamespaced = name && name.indexOf('.') !== -1; const possibleVariableAssignment = !extend && !isNamespaced; @@ -51,44 +45,46 @@ export default function iife( } if (extend) { - deps.unshift(`(${thisProp(name)} = ${thisProp(name)} || {})`); + deps.unshift(`(${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{})`); args.unshift('exports'); } else if (namedExportsMode && hasExports) { deps.unshift('{}'); args.unshift('exports'); } - const useStrict = options.strict !== false ? `${indentString}'use strict';\n\n` : ``; + const useStrict = options.strict !== false ? `${t}'use strict';${nl}${nl}` : ``; - let wrapperIntro = `(function (${args}) {\n${useStrict}`; + let wrapperIntro = `(function${_}(${args})${_}{${nl}${useStrict}`; if (hasExports && !extend) { wrapperIntro = - (isNamespaced ? thisProp(name) : `${graph.varOrConst} ${name}`) + ` = ${wrapperIntro}`; + (isNamespaced ? thisProp(name) : `${graph.varOrConst}${_}${name}`) + + `${_}=${_}${wrapperIntro}`; } if (isNamespaced) { - wrapperIntro = setupNamespace(name, 'this', false, options.globals) + wrapperIntro; + wrapperIntro = + setupNamespace(name, 'this', false, options.globals, options.compact) + wrapperIntro; } - let wrapperOutro = `\n\n}(${deps}));`; + let wrapperOutro = `${nl}${nl}}(${deps}));`; if (!extend && namedExportsMode && hasExports) { - wrapperOutro = `\n\n${indentString}return exports;${wrapperOutro}`; + wrapperOutro = `${nl}${nl}${t}return exports;${wrapperOutro}`; } // var foo__default = 'default' in foo ? foo['default'] : foo; const interopBlock = getInteropBlock(dependencies, options, graph.varOrConst); - if (interopBlock) magicString.prepend(interopBlock + '\n\n'); + if (interopBlock) magicString.prepend(interopBlock + nl + nl); if (intro) magicString.prepend(intro); - const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop); - if (exportBlock) magicString.append('\n\n' + exportBlock); + const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact); + if (exportBlock) magicString.append(nl + nl + exportBlock); if (outro) magicString.append(outro); return magicString - .indent(indentString) + .indent(t) .prepend(wrapperIntro) .append(wrapperOutro); } diff --git a/src/finalisers/shared/esModuleExport.ts b/src/finalisers/shared/esModuleExport.ts index 7764bdc7071..6f1d73a90b4 100644 --- a/src/finalisers/shared/esModuleExport.ts +++ b/src/finalisers/shared/esModuleExport.ts @@ -1 +1,2 @@ -export default `Object.defineProperty(exports, '__esModule', { value: true });`; +export const esModuleExport = `Object.defineProperty(exports, '__esModule', { value: true });`; +export const compactEsModuleExport = `Object.defineProperty(exports,'__esModule',{value:true});`; diff --git a/src/finalisers/shared/getExportBlock.ts b/src/finalisers/shared/getExportBlock.ts index 68de34c6d63..30de069c3eb 100644 --- a/src/finalisers/shared/getExportBlock.ts +++ b/src/finalisers/shared/getExportBlock.ts @@ -4,6 +4,7 @@ export default function getExportBlock( exports: ChunkExports, dependencies: ChunkDependencies, namedExportsMode: boolean, + compact: boolean, interop: boolean, mechanism = 'return' ) { @@ -32,6 +33,8 @@ export default function getExportBlock( return `${mechanism} ${local};`; } + const _ = compact ? '' : ' '; + let exportBlock = ''; // star exports must always output first for precedence @@ -39,9 +42,8 @@ export default function getExportBlock( if (reexports && namedExportsMode) { reexports.forEach(specifier => { if (specifier.reexported === '*') { - exportBlock += `${ - exportBlock ? '\n' : '' - }Object.keys(${name}).forEach(function (key) { exports[key] = ${name}[key]; });`; + if (!compact && exportBlock) exportBlock += '\n'; + exportBlock += `Object.keys(${name}).forEach(function${_}(key)${_}{${_}exports[key]${_}=${_}${name}[key];${_}});`; } }); } @@ -60,19 +62,17 @@ export default function getExportBlock( reexports.some( specifier => specifier.imported !== 'default' && specifier.imported !== '*' )); - if (exportsNamesOrNamespace) { - exportBlock += `${exportBlock ? '\n' : ''}exports.${specifier.reexported} = ${name}${ - interop !== false ? '__default' : '.default' - };`; - } else { - exportBlock += `${exportBlock ? '\n' : ''}exports.${specifier.reexported} = ${name};`; - } + if (exportBlock && !compact) exportBlock += '\n'; + if (exportsNamesOrNamespace) + exportBlock += `exports.${specifier.reexported}${_}=${_}${name}${interop !== false ? '__default' : '.default'};`; + else + exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`; } else if (specifier.imported !== '*') { - exportBlock += `${exportBlock ? '\n' : ''}exports.${specifier.reexported} = ${name}.${ - specifier.imported - };`; + if (exportBlock && !compact) exportBlock += '\n'; + exportBlock += `exports.${specifier.reexported}${_}=${_}${name}.${specifier.imported};`; } else if (specifier.reexported !== '*') { - exportBlock += `${exportBlock ? '\n' : ''}exports.${specifier.reexported} = ${name};`; + if (exportBlock && !compact) exportBlock += '\n'; + exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`; } }); } @@ -84,10 +84,8 @@ export default function getExportBlock( if (lhs === rhs) { return; } - if (exportBlock) { - exportBlock += '\n'; - } - exportBlock += `${lhs} = ${rhs};`; + if (exportBlock && !compact) exportBlock += '\n'; + exportBlock += `${lhs}${_}=${_}${rhs};`; }); return exportBlock; diff --git a/src/finalisers/shared/getInteropBlock.ts b/src/finalisers/shared/getInteropBlock.ts index 9ccdaa673eb..1bed875bf06 100644 --- a/src/finalisers/shared/getInteropBlock.ts +++ b/src/finalisers/shared/getInteropBlock.ts @@ -12,11 +12,16 @@ export default function getInteropBlock( if (!exportsDefault || options.interop === false) return null; - if (exportsNames) + if (exportsNames) { + if (options.compact) + return `${varOrConst} ${name}__default='default'in ${name}?${name}['default']:${name};`; return `${varOrConst} ${name}__default = 'default' in ${name} ? ${name}['default'] : ${name};`; + } + if (options.compact) + return `${name}=${name}&&${name}.hasOwnProperty('default')?${name}['default']:${name};`; return `${name} = ${name} && ${name}.hasOwnProperty('default') ? ${name}['default'] : ${name};`; }) .filter(Boolean) - .join('\n'); + .join(options.compact ? '' : '\n'); } diff --git a/src/finalisers/shared/setupNamespace.ts b/src/finalisers/shared/setupNamespace.ts index 222663869a3..e35d0afc3e5 100644 --- a/src/finalisers/shared/setupNamespace.ts +++ b/src/finalisers/shared/setupNamespace.ts @@ -5,22 +5,33 @@ export default function setupNamespace( name: string, root: string, forAssignment: boolean, - globals: GlobalsOption + globals: GlobalsOption, + compact: boolean ) { const parts = name.split('.'); if (globals) { parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0]; } + const _ = compact ? '' : ' '; + const last = parts.pop(); let acc = root; if (forAssignment) { return parts - .map(part => ((acc += property(part)), `${acc} = ${acc} || {}`)) + .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`)) .concat(`${acc}${property(last)}`) - .join(', '); + .join(`,${_}`); } else { - return parts.map(part => ((acc += property(part)), `${acc} = ${acc} || {};`)).join('\n') + '\n'; + return ( + parts + .map( + part => ( + (acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}` + ) + ) + .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n') + ); } } diff --git a/src/finalisers/system.ts b/src/finalisers/system.ts index ffd11cc3d9a..2b5137753b2 100644 --- a/src/finalisers/system.ts +++ b/src/finalisers/system.ts @@ -20,8 +20,11 @@ function getStarExcludes({ dependencies, exports }: ModuleDeclarations) { export default function system( magicString: MagicStringBundle, { graph, indentString: t, intro, outro, dependencies, exports }: FinaliserOptions, - outputOptions: OutputOptions + options: OutputOptions ) { + const nl = options.compact ? '' : '\n'; + const _ = options.compact ? '' : ' '; + const dependencyIds = dependencies.map(m => `'${m.id}'`); const importBindings: string[] = []; @@ -35,9 +38,9 @@ export default function system( imports.forEach(specifier => { importBindings.push(specifier.local); if (specifier.imported === '*') { - setter.push(`${specifier.local} = module;`); + setter.push(`${specifier.local}${_}=${_}module;`); } else { - setter.push(`${specifier.local} = module.${specifier.imported};`); + setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`); } }); } @@ -57,26 +60,26 @@ export default function system( starExcludes = getStarExcludes({ dependencies, exports }); } if (!createdSetter) { - setter.push(`${varOrConst} _setter = {};`); + setter.push(`${varOrConst} _setter${_}=${_}{};`); createdSetter = true; } - setter.push(`for (var _$p in module) {`); - setter.push(`${t}if (!_starExcludes[_$p]) _setter[_$p] = module[_$p];`); + setter.push(`for${_}(var _$p${_}in${_}module)${_}{`); + setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`); setter.push('}'); }); // star import reexport reexports.forEach(specifier => { if (specifier.imported !== '*' || specifier.reexported === '*') return; - setter.push(`exports('${specifier.reexported}', module);`); + setter.push(`exports('${specifier.reexported}',${_}module);`); }); // reexports reexports.forEach(specifier => { if (specifier.reexported === '*' || specifier.imported === '*') return; if (!createdSetter) { - setter.push(`${varOrConst} _setter = {};`); + setter.push(`${varOrConst} _setter${_}=${_}{};`); createdSetter = true; } - setter.push(`_setter.${specifier.reexported} = module.${specifier.imported};`); + setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`); }); if (createdSetter) { setter.push('exports(_setter);'); @@ -84,44 +87,50 @@ export default function system( } else { // single reexport reexports.forEach(specifier => { - setter.push(`exports('${specifier.reexported}', module.${specifier.imported});`); + setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`); }); } } - setters.push(setter.join(`\n${t}${t}${t}`)); + setters.push(setter.join(`${nl}${t}${t}${t}`)); }); // function declarations hoist const functionExports: string[] = []; exports.forEach(expt => { - if (expt.hoisted) functionExports.push(`exports('${expt.exported}', ${expt.local});`); + if (expt.hoisted) functionExports.push(`exports('${expt.exported}',${_}${expt.local});`); }); const starExcludesSection = !starExcludes ? '' - : `\n${t}${varOrConst} _starExcludes = { ${Array.from(starExcludes).join(': 1, ')}${ - starExcludes.size ? ': 1' : '' - } };`; + : `${nl}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join( + `:${_}1,${_}` + )}${starExcludes.size ? `:${_}1` : ''}${_}};`; const importBindingsSection = importBindings.length - ? `\n${t}var ${importBindings.join(', ')};` + ? `${nl}${t}var ${importBindings.join(`,${_}`)};` : ''; - const registeredName = outputOptions.name ? `'${outputOptions.name}', ` : ''; + const registeredName = options.name ? `'${options.name}',${_}` : ''; - const wrapperStart = `System.register(${registeredName}[${dependencyIds.join( - ', ' - )}], function (exports, module) { -${t}'use strict';${starExcludesSection}${importBindingsSection} -${t}return {${ + let wrapperStart = `System.register(${registeredName}[${dependencyIds.join( + `,${_}` + )}],${_}function${_}(exports,${_}module)${_}{${nl}`; + wrapperStart += `${t}'use strict';${starExcludesSection}${importBindingsSection}${nl}`; + wrapperStart += `${t}return${_}{${ setters.length - ? `\n${t}${t}setters: [${setters - .map(s => (s ? `function (module) {\n${t}${t}${t}${s}\n${t}${t}}` : `function () {}`)) - .join(', ')}],` + ? `${nl}${t}${t}setters:${_}[${setters + .map( + s => + s + ? `function${_}(module)${_}{${nl}${t}${t}${t}${s}${nl}${t}${t}}` + : `function${_}()${_}{}` + ) + .join(`,${_}`)}],` : '' - } -${t}${t}execute: function () { - -${functionExports.length ? `${t}${t}${t}` + functionExports.join(`\n${t}${t}${t}`) + '\n' : ''}`; + }${nl}`; + wrapperStart += `${t}${t}execute:${_}function${_}()${_}{${nl}${nl}`; + wrapperStart += `${ + functionExports.length ? `${t}${t}${t}` + functionExports.join(`${nl}${t}${t}${t}`) + nl : '' + }`; if (intro) magicString.prepend(intro); @@ -129,6 +138,6 @@ ${functionExports.length ? `${t}${t}${t}` + functionExports.join(`\n${t}${t}${t} return magicString .indent(`${t}${t}${t}`) - .append(`\n\n${t}${t}}\n${t}};\n});`) + .append(`${nl}${nl}${t}${t}}${nl}${t}};${nl}});`) .prepend(wrapperStart); } diff --git a/src/finalisers/umd.ts b/src/finalisers/umd.ts index 05561032316..22a11215992 100644 --- a/src/finalisers/umd.ts +++ b/src/finalisers/umd.ts @@ -1,7 +1,7 @@ import error from '../utils/error'; import getInteropBlock from './shared/getInteropBlock'; import getExportBlock from './shared/getExportBlock'; -import esModuleExport from './shared/esModuleExport'; +import { esModuleExport, compactEsModuleExport } from './shared/esModuleExport'; import { property, keypath } from './shared/sanitize'; import warnOnBuiltins from './shared/warnOnBuiltins'; import trimEmptyImports from './shared/trimEmptyImports'; @@ -15,29 +15,23 @@ function globalProp(name: string) { return `global${keypath(name)}`; } -function safeAccess(name: string) { +function safeAccess(name: string, compact: boolean) { const parts = name.split('.'); let acc = 'global'; - return parts.map(part => ((acc += property(part)), acc)).join(` && `); + return parts.map(part => ((acc += property(part)), acc)).join(compact ? '&&' : ` && `); } -const wrapperOutro = '\n\n})));'; - export default function umd( magicString: MagicStringBundle, - { - graph, - namedExportsMode, - hasExports, - indentString, - intro, - outro, - dependencies, - exports - }: FinaliserOptions, + { graph, namedExportsMode, hasExports, indentString: t, intro, outro, dependencies, exports }: FinaliserOptions, options: OutputOptions ) { + const _ = options.compact ? '' : ' '; + const nl = options.compact ? '' : '\n'; + + const wrapperOutro = nl + nl + '})));'; + if (hasExports && !options.name) { error({ code: 'INVALID_OPTION', @@ -58,8 +52,8 @@ export default function umd( amdDeps.unshift(`'exports'`); cjsDeps.unshift(`exports`); globalDeps.unshift( - `(${setupNamespace(options.name, 'global', true, options.globals)} = ${ - options.extend ? `${globalProp(options.name)} || ` : '' + `(${setupNamespace(options.name, 'global', true, options.globals, options.compact)}${_}=${_}${ + options.extend ? `${globalProp(options.name)}${_}||${_}` : '' }{})` ); @@ -69,68 +63,69 @@ export default function umd( const amdOptions = options.amd || {}; const amdParams = - (amdOptions.id ? `'${amdOptions.id}', ` : ``) + - (amdDeps.length ? `[${amdDeps.join(', ')}], ` : ``); + (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) + + (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``); const define = amdOptions.define || 'define'; - const cjsExport = !namedExportsMode && hasExports ? `module.exports = ` : ``; + const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``; const defaultExport = !namedExportsMode && hasExports - ? `${setupNamespace(options.name, 'global', true, options.globals)} = ` + ? `${setupNamespace(options.name, 'global', true, options.globals, options.compact)}${_}=${_}` : ''; - const useStrict = options.strict !== false ? ` 'use strict';` : ``; + const useStrict = options.strict !== false ? `${_}'use strict';${nl}` : ``; let globalExport; if (options.noConflict === true) { let factory; - if (!namedExportsMode && hasExports) { - factory = `var exports = factory(${globalDeps});`; + if (!namedExportsMode && hasExports) { + factory = `var exports${_}=${_}factory(${globalDeps});`; } else if (namedExportsMode) { const module = globalDeps.shift(); - factory = `var exports = ${module}; - factory(${['exports'].concat(globalDeps)});`; + factory = `var exports${_}=${_}${module};${nl}`; + factory += `${t}${t}factory(${['exports'].concat(globalDeps)});`; } - globalExport = `(function() { - var current = ${safeAccess(options.name)}; - ${factory} - ${globalProp(options.name)} = exports; - exports.noConflict = function() { ${globalProp(options.name)} = current; return exports; }; - })()`; + globalExport = `(function()${_}{${nl}`; + globalExport += `${t}${t}var current${_}=${_}${safeAccess( + options.name, + options.compact + )};${nl}`; + globalExport += `${t}${t}${factory}${nl}`; + globalExport += `${t}${t}${globalProp(options.name)}${_}=${_}exports;${nl}`; + globalExport += `${t}${t}exports.noConflict${_}=${_}function()${_}{${_}`; + globalExport += `${globalProp(options.name)}${_}=${_}current;${_}return exports${ + options.compact ? '' : '; ' + }};${nl}`; + globalExport += `${t}})()`; } else { globalExport = `(${defaultExport}factory(${globalDeps}))`; } - const wrapperIntro = `(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? ${cjsExport}factory(${cjsDeps.join( - ', ' - )}) : - typeof ${define} === 'function' && ${define}.amd ? ${define}(${amdParams}factory) : - ${globalExport}; - }(this, (function (${args}) {${useStrict} - - ` - .replace(/^\t\t/gm, '') - .replace(/^\t/gm, indentString || '\t'); + let wrapperIntro = `(function${_}(global,${_}factory)${_}{${nl}`; + wrapperIntro += `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?`; + wrapperIntro += `${_}${cjsExport}factory(${cjsDeps.join(`,${_}`)})${_}:${nl}`; + wrapperIntro += `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}factory)${_}:${nl}`; + wrapperIntro += `${t}${globalExport};${nl}`; + wrapperIntro += `}(this,${_}(function${_}(${args})${_}{${useStrict}${nl}`; // var foo__default = 'default' in foo ? foo['default'] : foo; const interopBlock = getInteropBlock(dependencies, options, graph.varOrConst); - if (interopBlock) magicString.prepend(interopBlock + '\n\n'); + if (interopBlock) magicString.prepend(interopBlock + nl + nl); if (intro) magicString.prepend(intro); - const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop); - if (exportBlock) magicString.append('\n\n' + exportBlock); + const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact); + if (exportBlock) magicString.append(nl + nl + exportBlock); if (namedExportsMode && hasExports && options.legacy !== true) - magicString.append(`\n\n${esModuleExport}`); + magicString.append(nl + nl + (options.compact ? compactEsModuleExport : esModuleExport)); if (outro) magicString.append(outro); return magicString .trim() - .indent(indentString) + .indent(t) .append(wrapperOutro) .prepend(wrapperIntro); } diff --git a/src/rollup/types.d.ts b/src/rollup/types.d.ts index e4218bb7f35..3b168e9c428 100644 --- a/src/rollup/types.d.ts +++ b/src/rollup/types.d.ts @@ -203,6 +203,7 @@ export interface OutputOptions { freeze?: boolean; namespaceToStringTag?: boolean; legacy?: boolean; + compact?: boolean; // undocumented? noConflict?: boolean; diff --git a/src/utils/mergeOptions.ts b/src/utils/mergeOptions.ts index 6d28b865967..6e93daf46bb 100644 --- a/src/utils/mergeOptions.ts +++ b/src/utils/mergeOptions.ts @@ -10,7 +10,9 @@ const createGetOption = (config: GenericConfigObject, command: GenericConfigObje ) => command[name] !== undefined ? command[name] - : config[name] !== undefined ? config[name] : defaultValue; + : config[name] !== undefined + ? config[name] + : defaultValue; const normalizeObjectOptionValue = (optionValue: any) => { if (!optionValue) { @@ -243,6 +245,7 @@ function getOutputOptions( banner: getOption('banner'), dir: getOption('dir'), chunkNames: getOption('chunkNames'), + compact: getOption('compact', false), entryNames: getOption('entryNames'), exports: getOption('exports'), extend: getOption('extend'), diff --git a/src/utils/renderHelpers.ts b/src/utils/renderHelpers.ts index 3a20958328f..37b6f0f2478 100644 --- a/src/utils/renderHelpers.ts +++ b/src/utils/renderHelpers.ts @@ -2,6 +2,7 @@ import { Node } from '../ast/nodes/shared/Node'; import MagicString from 'magic-string'; export interface RenderOptions { + compact: boolean; legacy: boolean; freeze: boolean; namespaceToStringTag: boolean; diff --git a/test/form/samples/compact/_config.js b/test/form/samples/compact/_config.js new file mode 100644 index 00000000000..33df6b58cfc --- /dev/null +++ b/test/form/samples/compact/_config.js @@ -0,0 +1,9 @@ +module.exports = { + description: 'compact output with compact: true', + options: { + output: { + name: 'foo', + compact: true + } + } +}; diff --git a/test/form/samples/compact/_expected/amd.js b/test/form/samples/compact/_expected/amd.js new file mode 100644 index 00000000000..476ea4fe36c --- /dev/null +++ b/test/form/samples/compact/_expected/amd.js @@ -0,0 +1,3 @@ +define(function(){'use strict';function foo () { + console.log( 'not indented' ); +}return foo;}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/cjs.js b/test/form/samples/compact/_expected/cjs.js new file mode 100644 index 00000000000..06e2d077b8f --- /dev/null +++ b/test/form/samples/compact/_expected/cjs.js @@ -0,0 +1,3 @@ +'use strict';function foo () { + console.log( 'not indented' ); +}module.exports= foo; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/es.js b/test/form/samples/compact/_expected/es.js new file mode 100644 index 00000000000..3907abfec7f --- /dev/null +++ b/test/form/samples/compact/_expected/es.js @@ -0,0 +1,3 @@ +function foo () { + console.log( 'not indented' ); +}export default foo; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/iife.js b/test/form/samples/compact/_expected/iife.js new file mode 100644 index 00000000000..8931eb89fd6 --- /dev/null +++ b/test/form/samples/compact/_expected/iife.js @@ -0,0 +1,3 @@ +varfoo=(function(){'use strict';function foo () { + console.log( 'not indented' ); +}return foo;}()); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/system.js b/test/form/samples/compact/_expected/system.js new file mode 100644 index 00000000000..878e3965592 --- /dev/null +++ b/test/form/samples/compact/_expected/system.js @@ -0,0 +1,3 @@ +System.register([],function(exports,module){'use strict';return{execute:function(){exports('default',foo);function foo () { + console.log( 'not indented' ); +}}};}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/umd.js b/test/form/samples/compact/_expected/umd.js new file mode 100644 index 00000000000..f029694f9bd --- /dev/null +++ b/test/form/samples/compact/_expected/umd.js @@ -0,0 +1,3 @@ +(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global.foo=factory());}(this,(function(){'use strict';function foo () { + console.log( 'not indented' ); +}return foo;}))); \ No newline at end of file diff --git a/test/form/samples/compact/main.js b/test/form/samples/compact/main.js new file mode 100644 index 00000000000..e68e7b30b94 --- /dev/null +++ b/test/form/samples/compact/main.js @@ -0,0 +1,3 @@ +export default function foo () { + console.log( 'not indented' ); +} diff --git a/test/form/samples/indent-false/_expected/umd.js b/test/form/samples/indent-false/_expected/umd.js index 22e4c7d96f7..fcd04052aae 100644 --- a/test/form/samples/indent-false/_expected/umd.js +++ b/test/form/samples/indent-false/_expected/umd.js @@ -1,7 +1,7 @@ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.foo = factory()); +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global.foo = factory()); }(this, (function () { 'use strict'; function foo () { diff --git a/test/misc/optionList.js b/test/misc/optionList.js index 20c94621625..2e511b9ebfb 100644 --- a/test/misc/optionList.js +++ b/test/misc/optionList.js @@ -1,3 +1,3 @@ exports.input = 'acorn, acornInjectPlugins, cache, chunkGroupingSize, context, entry, experimentalCodeSplitting, experimentalDynamicImport, experimentalPreserveModules, external, input, manualChunks, moduleContext, onwarn, optimizeChunks, perf, plugins, preferConst, preserveSymlinks, treeshake, watch'; -exports.flags = 'acorn, acornInjectPlugins, amd, banner, c, cache, chunkGroupingSize, chunkNames, config, context, dir, e, entry, entryNames, environment, experimentalCodeSplitting, experimentalDynamicImport, experimentalPreserveModules, exports, extend, external, f, file, footer, format, freeze, g, globals, h, i, indent, input, interop, intro, l, legacy, m, manualChunks, moduleContext, n, name, namespaceToStringTag, noConflict, o, onwarn, optimizeChunks, outro, paths, perf, plugins, preferConst, preserveSymlinks, silent, sourcemap, sourcemapFile, strict, treeshake, v, w, watch'; -exports.output = 'amd, banner, dir, chunkNames, entryNames, exports, extend, file, footer, format, freeze, globals, indent, interop, intro, legacy, name, namespaceToStringTag, noConflict, outro, paths, sourcemap, sourcemapFile, strict'; +exports.flags = 'acorn, acornInjectPlugins, amd, banner, c, cache, chunkGroupingSize, chunkNames, compact, config, context, dir, e, entry, entryNames, environment, experimentalCodeSplitting, experimentalDynamicImport, experimentalPreserveModules, exports, extend, external, f, file, footer, format, freeze, g, globals, h, i, indent, input, interop, intro, l, legacy, m, manualChunks, moduleContext, n, name, namespaceToStringTag, noConflict, o, onwarn, optimizeChunks, outro, paths, perf, plugins, preferConst, preserveSymlinks, silent, sourcemap, sourcemapFile, strict, treeshake, v, w, watch'; +exports.output = 'amd, banner, dir, chunkNames, compact, entryNames, exports, extend, file, footer, format, freeze, globals, indent, interop, intro, legacy, name, namespaceToStringTag, noConflict, outro, paths, sourcemap, sourcemapFile, strict'; From b16d18e0945f91d9c03646ae22952b2c49f9d51e Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Sun, 22 Apr 2018 23:35:51 +0200 Subject: [PATCH 02/14] include depenency in compact test --- test/form/samples/compact/_expected/amd.js | 4 ++-- test/form/samples/compact/_expected/cjs.js | 4 ++-- test/form/samples/compact/_expected/es.js | 4 ++-- test/form/samples/compact/_expected/iife.js | 6 +++--- test/form/samples/compact/_expected/system.js | 4 ++-- test/form/samples/compact/_expected/umd.js | 4 ++-- test/form/samples/compact/main.js | 3 ++- 7 files changed, 15 insertions(+), 14 deletions(-) diff --git a/test/form/samples/compact/_expected/amd.js b/test/form/samples/compact/_expected/amd.js index 476ea4fe36c..25f26840c75 100644 --- a/test/form/samples/compact/_expected/amd.js +++ b/test/form/samples/compact/_expected/amd.js @@ -1,3 +1,3 @@ -define(function(){'use strict';function foo () { - console.log( 'not indented' ); +define(['external'],function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { + console.log( x ); }return foo;}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/cjs.js b/test/form/samples/compact/_expected/cjs.js index 06e2d077b8f..efa715c5862 100644 --- a/test/form/samples/compact/_expected/cjs.js +++ b/test/form/samples/compact/_expected/cjs.js @@ -1,3 +1,3 @@ -'use strict';function foo () { - console.log( 'not indented' ); +'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e};${varOrConst} x=_interopDefault(require('external'))function foo () { + console.log( x ); }module.exports= foo; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/es.js b/test/form/samples/compact/_expected/es.js index 3907abfec7f..29c61ff9aea 100644 --- a/test/form/samples/compact/_expected/es.js +++ b/test/form/samples/compact/_expected/es.js @@ -1,3 +1,3 @@ -function foo () { - console.log( 'not indented' ); +import x from'external';function foo () { + console.log( x ); }export default foo; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/iife.js b/test/form/samples/compact/_expected/iife.js index 8931eb89fd6..936fc374b07 100644 --- a/test/form/samples/compact/_expected/iife.js +++ b/test/form/samples/compact/_expected/iife.js @@ -1,3 +1,3 @@ -varfoo=(function(){'use strict';function foo () { - console.log( 'not indented' ); -}return foo;}()); \ No newline at end of file +varfoo=(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { + console.log( x ); +}return foo;}(x)); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/system.js b/test/form/samples/compact/_expected/system.js index 878e3965592..204b1a63e63 100644 --- a/test/form/samples/compact/_expected/system.js +++ b/test/form/samples/compact/_expected/system.js @@ -1,3 +1,3 @@ -System.register([],function(exports,module){'use strict';return{execute:function(){exports('default',foo);function foo () { - console.log( 'not indented' ); +System.register(['external'],function(exports,module){'use strict';var x;return{setters:[function(module){x=module.default;}],execute:function(){exports('default',foo);function foo () { + console.log( x ); }}};}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/umd.js b/test/form/samples/compact/_expected/umd.js index f029694f9bd..ff35a37b4c3 100644 --- a/test/form/samples/compact/_expected/umd.js +++ b/test/form/samples/compact/_expected/umd.js @@ -1,3 +1,3 @@ -(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global.foo=factory());}(this,(function(){'use strict';function foo () { - console.log( 'not indented' ); +(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory(require('external')):typeof define==='function'&&define.amd?define(['external'],factory):(global.foo=factory(global.x));}(this,(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { + console.log( x ); }return foo;}))); \ No newline at end of file diff --git a/test/form/samples/compact/main.js b/test/form/samples/compact/main.js index e68e7b30b94..58ad4ee00c3 100644 --- a/test/form/samples/compact/main.js +++ b/test/form/samples/compact/main.js @@ -1,3 +1,4 @@ +import x from 'external'; export default function foo () { - console.log( 'not indented' ); + console.log( x ); } From 2065aa44f37df3af3d63f0372aa12e97aa5575a6 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Sun, 22 Apr 2018 23:40:10 +0200 Subject: [PATCH 03/14] compact cjs test fix --- src/finalisers/cjs.ts | 3 ++- test/form/samples/compact/_expected/cjs.js | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index 7f76fc70552..dc390027b01 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -45,7 +45,7 @@ export default function cjs( definingVariable = false; importBlock += `require('${id}')`; } else { - importBlock += definingVariable ? ',' : ';${varOrConst} '; + importBlock += definingVariable ? ',' : `;${varOrConst} `; definingVariable = true; if (!interop || isChunk || !exportsDefault || !namedExportsMode) { @@ -59,6 +59,7 @@ export default function cjs( } } ); + if (importBlock.length) importBlock += ';'; } else { importBlock = dependencies .map(({ id, isChunk, name, reexports, imports, exportsNames, exportsDefault }) => { diff --git a/test/form/samples/compact/_expected/cjs.js b/test/form/samples/compact/_expected/cjs.js index efa715c5862..b1d7bdbcf74 100644 --- a/test/form/samples/compact/_expected/cjs.js +++ b/test/form/samples/compact/_expected/cjs.js @@ -1,3 +1,3 @@ -'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e};${varOrConst} x=_interopDefault(require('external'))function foo () { +'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e};var x=_interopDefault(require('external'));function foo () { console.log( x ); }module.exports= foo; \ No newline at end of file From bccb7aad9a38da53b718498c48b30324120379be Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Sun, 22 Apr 2018 23:41:21 +0200 Subject: [PATCH 04/14] update cli test cases --- test/cli/samples/indent-none/_expected.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/cli/samples/indent-none/_expected.js b/test/cli/samples/indent-none/_expected.js index 343dda26134..74b5c2e3420 100644 --- a/test/cli/samples/indent-none/_expected.js +++ b/test/cli/samples/indent-none/_expected.js @@ -1,7 +1,7 @@ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory() : - typeof define === 'function' && define.amd ? define(factory) : - (factory()); +typeof exports === 'object' && typeof module !== 'undefined' ? factory() : +typeof define === 'function' && define.amd ? define(factory) : +(factory()); }(this, (function () { 'use strict'; assert.equal( 1 + 1, 2 ); From d0640bd4fb0f984fb20bdfbbd979ee2ad71379dc Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Mon, 23 Apr 2018 02:19:56 +0200 Subject: [PATCH 05/14] ensure compact esmodule export --- src/finalisers/cjs.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index dc390027b01..2f9e47c315f 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -24,7 +24,7 @@ export default function cjs( intro = (options.strict === false ? intro : `'use strict';${nl}${nl}${intro}`) + (namedExportsMode && hasExports && options.legacy !== true && isEntryModuleFacade - ? `${esModuleExport}${nl}${nl}` + ? `${options.compact ? compactEsModuleExport : esModuleExport}${nl}${nl}` : ''); let needsInterop = false; From 0af1a6fa7af7fb9f64f80b1faa79336aa8ddf865 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Mon, 23 Apr 2018 02:24:08 +0200 Subject: [PATCH 06/14] remove unnecessary semicolon in cjs output --- src/finalisers/cjs.ts | 2 +- test/form/samples/compact/_expected/cjs.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index 2f9e47c315f..bdc40e2c8b5 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -45,7 +45,7 @@ export default function cjs( definingVariable = false; importBlock += `require('${id}')`; } else { - importBlock += definingVariable ? ',' : `;${varOrConst} `; + importBlock += definingVariable ? ',' : `${importBlock ? ';' : ''}${varOrConst} `; definingVariable = true; if (!interop || isChunk || !exportsDefault || !namedExportsMode) { diff --git a/test/form/samples/compact/_expected/cjs.js b/test/form/samples/compact/_expected/cjs.js index b1d7bdbcf74..f8b4faab65d 100644 --- a/test/form/samples/compact/_expected/cjs.js +++ b/test/form/samples/compact/_expected/cjs.js @@ -1,3 +1,3 @@ -'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e};var x=_interopDefault(require('external'));function foo () { +'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}var x=_interopDefault(require('external'));function foo () { console.log( x ); }module.exports= foo; \ No newline at end of file From 0d24ab8c907d31fe466d139c481e0384bdd45a1e Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Wed, 25 Apr 2018 01:50:34 +0200 Subject: [PATCH 07/14] fix missing space --- src/finalisers/iife.ts | 3 +-- test/form/samples/compact/_expected/iife.js | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/finalisers/iife.ts b/src/finalisers/iife.ts index e58b6719f5d..1658989ce98 100644 --- a/src/finalisers/iife.ts +++ b/src/finalisers/iife.ts @@ -58,8 +58,7 @@ export default function iife( if (hasExports && !extend) { wrapperIntro = - (isNamespaced ? thisProp(name) : `${graph.varOrConst}${_}${name}`) + - `${_}=${_}${wrapperIntro}`; + (isNamespaced ? thisProp(name) : `${graph.varOrConst} ${name}`) + `${_}=${_}${wrapperIntro}`; } if (isNamespaced) { diff --git a/test/form/samples/compact/_expected/iife.js b/test/form/samples/compact/_expected/iife.js index 936fc374b07..2ffdc56edae 100644 --- a/test/form/samples/compact/_expected/iife.js +++ b/test/form/samples/compact/_expected/iife.js @@ -1,3 +1,3 @@ -varfoo=(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { +var foo=(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { console.log( x ); }return foo;}(x)); \ No newline at end of file From 0ecc0ea5e8cadfb5e329f7482efead4f28b6c0d4 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Wed, 25 Apr 2018 22:31:49 +0200 Subject: [PATCH 08/14] mangle chunk boundaries in compact mode --- src/Chunk.ts | 2 +- src/finalisers/amd.ts | 2 +- src/finalisers/cjs.ts | 2 +- src/finalisers/shared/getExportBlock.ts | 10 +++++----- .../samples/chunking-compact/_config.js | 9 +++++++++ .../chunking-compact/_expected/amd/chunk-1e9855f7.js | 6 ++++++ .../samples/chunking-compact/_expected/amd/main1.js | 8 ++++++++ .../samples/chunking-compact/_expected/amd/main2.js | 12 ++++++++++++ .../chunking-compact/_expected/cjs/chunk-992f09ca.js | 6 ++++++ .../samples/chunking-compact/_expected/cjs/main1.js | 8 ++++++++ .../samples/chunking-compact/_expected/cjs/main2.js | 12 ++++++++++++ .../chunking-compact/_expected/es/chunk-5b60a9d9.js | 6 ++++++ .../samples/chunking-compact/_expected/es/main1.js | 8 ++++++++ .../samples/chunking-compact/_expected/es/main2.js | 12 ++++++++++++ .../_expected/system/chunk-ad0e6b97.js | 6 ++++++ .../chunking-compact/_expected/system/main1.js | 8 ++++++++ .../chunking-compact/_expected/system/main2.js | 12 ++++++++++++ test/chunking-form/samples/chunking-compact/dep1.js | 3 +++ test/chunking-form/samples/chunking-compact/dep2.js | 6 ++++++ test/chunking-form/samples/chunking-compact/dep3.js | 6 ++++++ test/chunking-form/samples/chunking-compact/lib1.js | 6 ++++++ test/chunking-form/samples/chunking-compact/lib2.js | 3 +++ test/chunking-form/samples/chunking-compact/main1.js | 9 +++++++++ test/chunking-form/samples/chunking-compact/main2.js | 9 +++++++++ test/form/samples/compact/_expected/cjs.js | 2 +- 25 files changed, 164 insertions(+), 9 deletions(-) create mode 100644 test/chunking-form/samples/chunking-compact/_config.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/amd/main1.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/amd/main2.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/es/main1.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/es/main2.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/system/main1.js create mode 100644 test/chunking-form/samples/chunking-compact/_expected/system/main2.js create mode 100644 test/chunking-form/samples/chunking-compact/dep1.js create mode 100644 test/chunking-form/samples/chunking-compact/dep2.js create mode 100644 test/chunking-form/samples/chunking-compact/dep3.js create mode 100644 test/chunking-form/samples/chunking-compact/lib1.js create mode 100644 test/chunking-form/samples/chunking-compact/lib2.js create mode 100644 test/chunking-form/samples/chunking-compact/main1.js create mode 100644 test/chunking-form/samples/chunking-compact/main2.js diff --git a/src/Chunk.ts b/src/Chunk.ts index 5bb16e26147..027decbd586 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -360,7 +360,7 @@ export default class Chunk { generateInternalExports(options: OutputOptions) { if (this.isEntryModuleFacade) return; - const mangle = options.format === 'system' || options.format === 'es'; + const mangle = options.format === 'system' || options.format === 'es' || options.compact; let i = 0, safeExportName: string; this.exportNames = Object.create(null); diff --git a/src/finalisers/amd.ts b/src/finalisers/amd.ts index 33b565c0ea7..c161bfbe4fe 100644 --- a/src/finalisers/amd.ts +++ b/src/finalisers/amd.ts @@ -63,7 +63,7 @@ export default function amd( if (intro) magicString.prepend(intro); - const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop); + const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact); if (exportBlock) magicString.append(nl + nl + exportBlock); if (namedExportsMode && hasExports && options.legacy !== true && isEntryModuleFacade) magicString.append(`${nl}${nl}${options.compact ? compactEsModuleExport : esModuleExport}`); diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index bdc40e2c8b5..64caab1889c 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -96,7 +96,7 @@ export default function cjs( namedExportsMode, options.interop, options.compact, - `module.exports${_}=` + `module.exports${_}=${_}` ); magicString.prepend(intro); diff --git a/src/finalisers/shared/getExportBlock.ts b/src/finalisers/shared/getExportBlock.ts index 30de069c3eb..118f69adf88 100644 --- a/src/finalisers/shared/getExportBlock.ts +++ b/src/finalisers/shared/getExportBlock.ts @@ -4,10 +4,12 @@ export default function getExportBlock( exports: ChunkExports, dependencies: ChunkDependencies, namedExportsMode: boolean, - compact: boolean, interop: boolean, - mechanism = 'return' + compact: boolean, + mechanism = 'return ' ) { + const _ = compact ? '' : ' '; + if (!namedExportsMode) { let local; exports.some(expt => { @@ -30,11 +32,9 @@ export default function getExportBlock( }); }); } - return `${mechanism} ${local};`; + return `${mechanism}${local};`; } - const _ = compact ? '' : ' '; - let exportBlock = ''; // star exports must always output first for precedence diff --git a/test/chunking-form/samples/chunking-compact/_config.js b/test/chunking-form/samples/chunking-compact/_config.js new file mode 100644 index 00000000000..fa95c32d1ff --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_config.js @@ -0,0 +1,9 @@ +module.exports = { + description: 'chunking compact and mangled output', + options: { + input: ['main1.js', 'main2.js'], + output: { + compact: true + } + } +}; diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js b/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js new file mode 100644 index 00000000000..f793b3c38f3 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js @@ -0,0 +1,6 @@ +define(['exports'],function(exports){'use strict';function fn () { + console.log('lib2 fn'); +}function fn$1 () { + fn(); + console.log('dep2 fn'); +}exports.a=fn$1;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js b/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js new file mode 100644 index 00000000000..3e115fe9f2e --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js @@ -0,0 +1,8 @@ +define(['./chunk-1e9855f7.js'],function(__chunk_1){'use strict';function fn () { + console.log('dep1 fn'); +}class Main1 { + constructor () { + fn(); + __chunk_1.a(); + } +}return Main1;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js b/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js new file mode 100644 index 00000000000..42ff9bbd118 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js @@ -0,0 +1,12 @@ +define(['external','./chunk-1e9855f7.js'],function(external,__chunk_1){'use strict';function fn () { + console.log('lib1 fn'); + external.fn(); +}function fn$1 () { + fn(); + console.log('dep3 fn'); +}class Main2 { + constructor () { + fn$1(); + __chunk_1.a(); + } +}return Main2;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js new file mode 100644 index 00000000000..36b2112ae76 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js @@ -0,0 +1,6 @@ +'use strict';function fn () { + console.log('lib2 fn'); +}function fn$1 () { + fn(); + console.log('dep2 fn'); +}exports.a=fn$1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js new file mode 100644 index 00000000000..43df57fd5e6 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js @@ -0,0 +1,8 @@ +'use strict';var __chunk_1=require('./chunk-992f09ca.js');function fn () { + console.log('dep1 fn'); +}class Main1 { + constructor () { + fn(); + __chunk_1.a(); + } +}module.exports=Main1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js new file mode 100644 index 00000000000..ef8939f2eb3 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js @@ -0,0 +1,12 @@ +'use strict';var external=require('external'),__chunk_1=require('./chunk-992f09ca.js');function fn () { + console.log('lib1 fn'); + external.fn(); +}function fn$1 () { + fn(); + console.log('dep3 fn'); +}class Main2 { + constructor () { + fn$1(); + __chunk_1.a(); + } +}module.exports=Main2; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js b/test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js new file mode 100644 index 00000000000..b8c1ff4df40 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js @@ -0,0 +1,6 @@ +function fn () { + console.log('lib2 fn'); +}function fn$1 () { + fn(); + console.log('dep2 fn'); +}export{fn$1 as a}; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/main1.js b/test/chunking-form/samples/chunking-compact/_expected/es/main1.js new file mode 100644 index 00000000000..0105d5c2a5f --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/es/main1.js @@ -0,0 +1,8 @@ +import {a as fn}from'./chunk-5b60a9d9.js';function fn$1 () { + console.log('dep1 fn'); +}class Main1 { + constructor () { + fn$1(); + fn(); + } +}export default Main1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/main2.js b/test/chunking-form/samples/chunking-compact/_expected/es/main2.js new file mode 100644 index 00000000000..6390ed6812d --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/es/main2.js @@ -0,0 +1,12 @@ +import {fn}from'external';import {a as fn$1}from'./chunk-5b60a9d9.js';function fn$2 () { + console.log('lib1 fn'); + fn(); +}function fn$3 () { + fn$2(); + console.log('dep3 fn'); +}class Main2 { + constructor () { + fn$3(); + fn$1(); + } +}export default Main2; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js new file mode 100644 index 00000000000..18b08415474 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js @@ -0,0 +1,6 @@ +System.register([],function(exports,module){'use strict';return{execute:function(){exports('a',fn$1);function fn () { + console.log('lib2 fn'); +}function fn$1 () { + fn(); + console.log('dep2 fn'); +}}};}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main1.js b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js new file mode 100644 index 00000000000..1b5dd7f4132 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js @@ -0,0 +1,8 @@ +System.register(['./chunk-ad0e6b97.js'],function(exports,module){'use strict';var fn;return{setters:[function(module){fn=module.a;}],execute:function(){function fn$1 () { + console.log('dep1 fn'); +}class Main1 { + constructor () { + fn$1(); + fn(); + } +} exports('default', Main1);}};}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main2.js b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js new file mode 100644 index 00000000000..6eab9d175f2 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js @@ -0,0 +1,12 @@ +System.register(['external','./chunk-ad0e6b97.js'],function(exports,module){'use strict';var fn,fn$1;return{setters:[function(module){fn=module.fn;},function(module){fn$1=module.a;}],execute:function(){function fn$2 () { + console.log('lib1 fn'); + fn(); +}function fn$3 () { + fn$2(); + console.log('dep3 fn'); +}class Main2 { + constructor () { + fn$3(); + fn$1(); + } +} exports('default', Main2);}};}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/dep1.js b/test/chunking-form/samples/chunking-compact/dep1.js new file mode 100644 index 00000000000..b67d0bbb2c1 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/dep1.js @@ -0,0 +1,3 @@ +export function fn () { + console.log('dep1 fn'); +} \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/dep2.js b/test/chunking-form/samples/chunking-compact/dep2.js new file mode 100644 index 00000000000..1549fc1644c --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/dep2.js @@ -0,0 +1,6 @@ +import { fn as libfn } from './lib2.js'; + +export function fn () { + libfn(); + console.log('dep2 fn'); +} \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/dep3.js b/test/chunking-form/samples/chunking-compact/dep3.js new file mode 100644 index 00000000000..f63072a5fc8 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/dep3.js @@ -0,0 +1,6 @@ +import { fn as libfn } from './lib1.js'; + +export function fn () { + libfn(); + console.log('dep3 fn'); +} \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/lib1.js b/test/chunking-form/samples/chunking-compact/lib1.js new file mode 100644 index 00000000000..399f3851399 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/lib1.js @@ -0,0 +1,6 @@ +import { fn as fn$1 } from 'external'; + +export function fn () { + console.log('lib1 fn'); + fn$1(); +} \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/lib2.js b/test/chunking-form/samples/chunking-compact/lib2.js new file mode 100644 index 00000000000..2d6d2cf0852 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/lib2.js @@ -0,0 +1,3 @@ +export function fn () { + console.log('lib2 fn'); +} \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/main1.js b/test/chunking-form/samples/chunking-compact/main1.js new file mode 100644 index 00000000000..8ac04f13d98 --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/main1.js @@ -0,0 +1,9 @@ +import { fn } from './dep1.js'; +import { fn as fn2 } from './dep2.js'; + +export default class Main1 { + constructor () { + fn(); + fn2(); + } +} \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/main2.js b/test/chunking-form/samples/chunking-compact/main2.js new file mode 100644 index 00000000000..29abc01f71a --- /dev/null +++ b/test/chunking-form/samples/chunking-compact/main2.js @@ -0,0 +1,9 @@ +import { fn } from './dep2.js'; +import { fn as fn2 } from './dep3.js'; + +export default class Main2 { + constructor () { + fn2(); + fn(); + } +} \ No newline at end of file diff --git a/test/form/samples/compact/_expected/cjs.js b/test/form/samples/compact/_expected/cjs.js index f8b4faab65d..9a24b7daab5 100644 --- a/test/form/samples/compact/_expected/cjs.js +++ b/test/form/samples/compact/_expected/cjs.js @@ -1,3 +1,3 @@ 'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}var x=_interopDefault(require('external'));function foo () { console.log( x ); -}module.exports= foo; \ No newline at end of file +}module.exports=foo; \ No newline at end of file From 099c4f721358b7a76d5cae18748b021488611ab5 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Sun, 6 May 2018 19:40:10 +0200 Subject: [PATCH 09/14] pr feedback --- src/Chunk.ts | 12 +++-- src/ast/nodes/Import.ts | 10 +++-- src/ast/variables/NamespaceVariable.ts | 16 ++++--- src/finalisers/amd.ts | 20 ++++++--- src/finalisers/cjs.ts | 10 ++--- src/finalisers/esm.ts | 18 ++++---- src/finalisers/iife.ts | 22 +++++---- src/finalisers/system.ts | 24 +++++----- src/finalisers/umd.ts | 45 ++++++++++--------- src/utils/addons.ts | 9 ++-- test/form/samples/compact/_config.js | 3 +- test/form/samples/compact/_expected/amd.js | 5 ++- test/form/samples/compact/_expected/cjs.js | 5 ++- test/form/samples/compact/_expected/es.js | 5 ++- test/form/samples/compact/_expected/iife.js | 5 ++- test/form/samples/compact/_expected/system.js | 3 +- test/form/samples/compact/_expected/umd.js | 5 ++- test/form/samples/compact/main.js | 2 + 18 files changed, 124 insertions(+), 95 deletions(-) diff --git a/src/Chunk.ts b/src/Chunk.ts index 027decbd586..3ffc97ebc96 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -730,7 +730,7 @@ export default class Chunk { this.usedModules = []; this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options); - const nl = options.compact ? '' : '\n'; + const n = options.compact ? '' : '\n'; if (this.graph.dynamicImport) this.prepareDynamicImports(); @@ -785,13 +785,13 @@ export default class Chunk { if (namespace.needsNamespaceBlock) { const rendered = namespace.renderBlock(renderOptions); - if (namespace.renderFirst()) hoistedSource += nl + rendered; + if (namespace.renderFirst()) hoistedSource += n + rendered; else magicString.addSource(new MagicString(rendered)); } } } - if (hoistedSource) magicString.prepend(hoistedSource + nl + nl); + if (hoistedSource) magicString.prepend(hoistedSource + n + n); this.renderedSource = magicString.trim(); this.renderedSourceLength = undefined; @@ -968,8 +968,6 @@ export default class Chunk { render(options: OutputOptions, addons: Addons) { timeStart('render format', 3); - const nl = options.compact ? '' : '\n'; - if (!this.renderedSource) throw new Error('Internal error: Chunk render called before preRender'); @@ -1025,8 +1023,8 @@ export default class Chunk { }, options ); - if (addons.banner) magicString.prepend(addons.banner + nl); - if (addons.footer) magicString.append(nl + addons.footer); + if (addons.banner) magicString.prepend(addons.banner); + if (addons.footer) magicString.append(addons.footer); const prevCode = magicString.toString(); timeEnd('render format', 3); diff --git a/src/ast/nodes/Import.ts b/src/ast/nodes/Import.ts index 85a70a15688..a2e1688852f 100644 --- a/src/ast/nodes/Import.ts +++ b/src/ast/nodes/Import.ts @@ -24,11 +24,13 @@ const getDynamicImportMechanism = (format: string, compact: boolean): DynamicImp } case 'amd': { const _ = compact ? '' : ' '; + const resolve = compact ? 'c' : 'resolve'; + const reject = compact ? 'e' : 'reject'; return { - left: `new Promise(function${_}(resolve,${_}reject)${_}{${_}require([`, - right: `],${_}resolve,${_}reject)${_}})`, - interopLeft: `new Promise(function${_}(resolve,${_}reject)${_}{${_}require([`, - interopRight: `],${_}function${_}(m)${_}{${_}resolve({${_}default:${_}m${_}})${_}},${_}reject)${_}})` + left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`, + right: `],${_}${resolve},${_}${reject})${_}})`, + interopLeft: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`, + interopRight: `],${_}function${_}(m)${_}{${_}${resolve}({${_}default:${_}m${_}})${_}},${_}${reject})${_}})` }; } case 'system': diff --git a/src/ast/variables/NamespaceVariable.ts b/src/ast/variables/NamespaceVariable.ts index 2f1e9139ed8..edc5322d8c2 100644 --- a/src/ast/variables/NamespaceVariable.ts +++ b/src/ast/variables/NamespaceVariable.ts @@ -49,24 +49,25 @@ export default class NamespaceVariable extends Variable { renderBlock(options: RenderOptions) { const _ = options.compact ? '' : ' '; const n = options.compact ? '' : '\n'; + const t = options.indent; const members = Object.keys(this.originals).map(name => { const original = this.originals[name]; if ((this.referencedEarly || original.isReassigned) && !options.legacy) { - return `${options.indent}get ${name}${_}()${_}{${_}return${_}${original.getName()};${_}}`; + return `${t}get ${name}${_}()${_}{${_}return${_}${original.getName()}${ + options.compact ? '' : ';' + }${_}}`; } if (options.legacy && reservedWords.indexOf(name) !== -1) name = `'${name}'`; - return `${options.indent}${name}: ${original.getName()}`; + return `${t}${name}: ${original.getName()}`; }); const name = this.getName(); const callee = options.freeze - ? `${options.compact ? '' : '/*#__PURE__*/'}${ - options.legacy ? `(Object.freeze${_}||${_}Object)` : `Object.freeze` - }` + ? `/*#__PURE__*/${options.legacy ? `(Object.freeze${_}||${_}Object)` : `Object.freeze`}` : ''; let output = `${this.context.varOrConst} ${name} = ${ @@ -76,11 +77,12 @@ export default class NamespaceVariable extends Variable { }`; if (options.namespaceToStringTag) { - const t = options.indent; output += `${n}if${_}(typeof Symbol${_}!==${_}'undefined'${_}&&${_}Symbol.toStringTag)${n}`; output += `${t}Object.defineProperty(${name},${_}Symbol.toStringTag,${_}{${_}value:${_}'Module'${_}});${n}`; output += `else${n}`; - output += `${t}Object.defineProperty(${name},${_}'toString',${_}{${_}value:${_}function${_}()${_}{${_}return${_}'[object Module]'${_}}${_}});${n}`; + output += `${t}Object.defineProperty(${name},${_}'toString',${_}{${_}value:${_}function${_}()${_}{${_}return${_}'[object Module]'${ + options.compact ? ';' : '' + }${_}}${_}});${n}`; output += `${callee}(${name});`; } diff --git a/src/finalisers/amd.ts b/src/finalisers/amd.ts index c161bfbe4fe..bf73b89834e 100644 --- a/src/finalisers/amd.ts +++ b/src/finalisers/amd.ts @@ -27,7 +27,7 @@ export default function amd( const deps = dependencies.map(m => `'${m.id}'`); const args = dependencies.map(m => m.name); - const nl = options.compact ? '' : '\n'; + const n = options.compact ? '' : '\n'; const _ = options.compact ? '' : ' '; if (namedExportsMode && hasExports) { @@ -55,22 +55,28 @@ export default function amd( const define = amdOptions.define || 'define'; const wrapperStart = `${define}(${params}function${_}(${args.join( `,${_}` - )})${_}{${useStrict}${nl}${nl}`; + )})${_}{${useStrict}${n}${n}`; // var foo__default = 'default' in foo ? foo['default'] : foo; const interopBlock = getInteropBlock(dependencies, options, graph.varOrConst); - if (interopBlock) magicString.prepend(interopBlock + nl + nl); + if (interopBlock) magicString.prepend(interopBlock + n + n); if (intro) magicString.prepend(intro); - const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact); - if (exportBlock) magicString.append(nl + nl + exportBlock); + const exportBlock = getExportBlock( + exports, + dependencies, + namedExportsMode, + options.interop, + options.compact + ); + if (exportBlock) magicString.append(n + n + exportBlock); if (namedExportsMode && hasExports && options.legacy !== true && isEntryModuleFacade) - magicString.append(`${nl}${nl}${options.compact ? compactEsModuleExport : esModuleExport}`); + magicString.append(`${n}${n}${options.compact ? compactEsModuleExport : esModuleExport}`); if (outro) magicString.append(outro); return magicString .indent(indentString) - .append(nl + nl + '});') + .append(n + n + '});') .prepend(wrapperStart); } diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index 64caab1889c..b930aa70e2e 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -18,13 +18,13 @@ export default function cjs( }: FinaliserOptions, options: OutputOptions ) { - const nl = options.compact ? '' : '\n'; + const n = options.compact ? '' : '\n'; const _ = options.compact ? '' : ' '; intro = - (options.strict === false ? intro : `'use strict';${nl}${nl}${intro}`) + + (options.strict === false ? intro : `'use strict';${n}${n}${intro}`) + (namedExportsMode && hasExports && options.legacy !== true && isEntryModuleFacade - ? `${options.compact ? compactEsModuleExport : esModuleExport}${nl}${nl}` + ? `${options.compact ? compactEsModuleExport : esModuleExport}${n}${n}` : ''); let needsInterop = false; @@ -88,7 +88,7 @@ export default function cjs( intro += `function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\n`; } - if (importBlock) intro += importBlock + nl + nl; + if (importBlock) intro += importBlock + n + n; const exportBlock = getExportBlock( exports, @@ -101,7 +101,7 @@ export default function cjs( magicString.prepend(intro); - if (exportBlock) magicString.append(nl + nl + exportBlock); + if (exportBlock) magicString.append(n + n + exportBlock); if (outro) magicString.append(outro); return magicString; diff --git a/src/finalisers/esm.ts b/src/finalisers/esm.ts index af2ce4a71a9..217ddd88333 100644 --- a/src/finalisers/esm.ts +++ b/src/finalisers/esm.ts @@ -10,7 +10,7 @@ export default function esm( options: OutputOptions ) { const _ = options.compact ? '' : ' '; - const nl = options.compact ? '' : '\n'; + const n = options.compact ? '' : '\n'; const importBlock = dependencies .map(({ id, reexports, imports, name }) => { @@ -23,7 +23,7 @@ export default function esm( const starImport = imports.find(specifier => specifier.imported === '*'); if (starImport) { output += `import${_}*${_}as ${starImport.local} from${_}'${id}';`; - if (imports.length > 1) output += nl; + if (imports.length > 1) output += n; } if (defaultImport && imports.length === 1) { output += `import ${defaultImport.local} from${_}'${id}';`; @@ -41,7 +41,7 @@ export default function esm( } } if (reexports) { - if (imports) output += nl; + if (imports) output += n; const starExport = reexports.find(specifier => specifier.reexported === '*'); const namespaceReexport = reexports.find( specifier => specifier.imported === '*' && specifier.reexported !== '*' @@ -51,14 +51,14 @@ export default function esm( if (reexports.length === 1) { return output; } - output += nl; + output += n; } if (namespaceReexport) { if ( !imports || !imports.some(specifier => specifier.imported === '*' && specifier.local === name) ) - output += `import${_}*${_}as ${name} from${_}'${id}';${nl}`; + output += `import${_}*${_}as ${name} from${_}'${id}';${n}`; output += `export${_}{${_}${ name === namespaceReexport.reexported ? name @@ -67,7 +67,7 @@ export default function esm( if (reexports.length === (starExport ? 2 : 1)) { return output; } - output += nl; + output += n; } output += `export${_}{${_}${reexports .filter(specifier => specifier !== starExport && specifier !== namespaceReexport) @@ -82,9 +82,9 @@ export default function esm( } return output; }) - .join(nl); + .join(n); - if (importBlock) intro += importBlock + nl + nl; + if (importBlock) intro += importBlock + n + n; if (intro) magicString.prepend(intro); const exportBlock: string[] = []; @@ -104,7 +104,7 @@ export default function esm( exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`); } - if (exportBlock.length) magicString.append(nl + nl + exportBlock.join(nl).trim()); + if (exportBlock.length) magicString.append(n + n + exportBlock.join(n).trim()); if (outro) magicString.append(outro); diff --git a/src/finalisers/iife.ts b/src/finalisers/iife.ts index 1658989ce98..f1c8c93cff7 100644 --- a/src/finalisers/iife.ts +++ b/src/finalisers/iife.ts @@ -18,7 +18,7 @@ export default function iife( options: OutputOptions ) { const _ = options.compact ? '' : ' '; - const nl = options.compact ? '' : '\n'; + const n = options.compact ? '' : '\n'; const { extend, name } = options; const isNamespaced = name && name.indexOf('.') !== -1; @@ -52,9 +52,9 @@ export default function iife( args.unshift('exports'); } - const useStrict = options.strict !== false ? `${t}'use strict';${nl}${nl}` : ``; + const useStrict = options.strict !== false ? `${t}'use strict';${n}${n}` : ``; - let wrapperIntro = `(function${_}(${args})${_}{${nl}${useStrict}`; + let wrapperIntro = `(function${_}(${args})${_}{${n}${useStrict}`; if (hasExports && !extend) { wrapperIntro = @@ -66,20 +66,26 @@ export default function iife( setupNamespace(name, 'this', false, options.globals, options.compact) + wrapperIntro; } - let wrapperOutro = `${nl}${nl}}(${deps}));`; + let wrapperOutro = `${n}${n}}(${deps}));`; if (!extend && namedExportsMode && hasExports) { - wrapperOutro = `${nl}${nl}${t}return exports;${wrapperOutro}`; + wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`; } // var foo__default = 'default' in foo ? foo['default'] : foo; const interopBlock = getInteropBlock(dependencies, options, graph.varOrConst); - if (interopBlock) magicString.prepend(interopBlock + nl + nl); + if (interopBlock) magicString.prepend(interopBlock + n + n); if (intro) magicString.prepend(intro); - const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact); - if (exportBlock) magicString.append(nl + nl + exportBlock); + const exportBlock = getExportBlock( + exports, + dependencies, + namedExportsMode, + options.interop, + options.compact + ); + if (exportBlock) magicString.append(n + n + exportBlock); if (outro) magicString.append(outro); return magicString diff --git a/src/finalisers/system.ts b/src/finalisers/system.ts index 2b5137753b2..1699e422f59 100644 --- a/src/finalisers/system.ts +++ b/src/finalisers/system.ts @@ -22,7 +22,7 @@ export default function system( { graph, indentString: t, intro, outro, dependencies, exports }: FinaliserOptions, options: OutputOptions ) { - const nl = options.compact ? '' : '\n'; + const n = options.compact ? '' : '\n'; const _ = options.compact ? '' : ' '; const dependencyIds = dependencies.map(m => `'${m.id}'`); @@ -91,7 +91,7 @@ export default function system( }); } } - setters.push(setter.join(`${nl}${t}${t}${t}`)); + setters.push(setter.join(`${n}${t}${t}${t}`)); }); // function declarations hoist @@ -102,34 +102,34 @@ export default function system( const starExcludesSection = !starExcludes ? '' - : `${nl}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join( + : `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join( `:${_}1,${_}` )}${starExcludes.size ? `:${_}1` : ''}${_}};`; const importBindingsSection = importBindings.length - ? `${nl}${t}var ${importBindings.join(`,${_}`)};` + ? `${n}${t}var ${importBindings.join(`,${_}`)};` : ''; const registeredName = options.name ? `'${options.name}',${_}` : ''; let wrapperStart = `System.register(${registeredName}[${dependencyIds.join( `,${_}` - )}],${_}function${_}(exports,${_}module)${_}{${nl}`; - wrapperStart += `${t}'use strict';${starExcludesSection}${importBindingsSection}${nl}`; + )}],${_}function${_}(exports,${_}module)${_}{${n}`; + wrapperStart += `${t}'use strict';${starExcludesSection}${importBindingsSection}${n}`; wrapperStart += `${t}return${_}{${ setters.length - ? `${nl}${t}${t}setters:${_}[${setters + ? `${n}${t}${t}setters:${_}[${setters .map( s => s - ? `function${_}(module)${_}{${nl}${t}${t}${t}${s}${nl}${t}${t}}` + ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}` : `function${_}()${_}{}` ) .join(`,${_}`)}],` : '' - }${nl}`; - wrapperStart += `${t}${t}execute:${_}function${_}()${_}{${nl}${nl}`; + }${n}`; + wrapperStart += `${t}${t}execute:${_}function${_}()${_}{${n}${n}`; wrapperStart += `${ - functionExports.length ? `${t}${t}${t}` + functionExports.join(`${nl}${t}${t}${t}`) + nl : '' + functionExports.length ? `${t}${t}${t}` + functionExports.join(`${n}${t}${t}${t}`) + n : '' }`; if (intro) magicString.prepend(intro); @@ -138,6 +138,6 @@ export default function system( return magicString .indent(`${t}${t}${t}`) - .append(`${nl}${nl}${t}${t}}${nl}${t}};${nl}});`) + .append(`${n}${n}${t}${t}}${n}${t}};${n}});`) .prepend(wrapperStart); } diff --git a/src/finalisers/umd.ts b/src/finalisers/umd.ts index 22a11215992..97f0656a5d4 100644 --- a/src/finalisers/umd.ts +++ b/src/finalisers/umd.ts @@ -28,9 +28,9 @@ export default function umd( options: OutputOptions ) { const _ = options.compact ? '' : ' '; - const nl = options.compact ? '' : '\n'; + const n = options.compact ? '' : '\n'; - const wrapperOutro = nl + nl + '})));'; + const wrapperOutro = n + n + '})));'; if (hasExports && !options.name) { error({ @@ -74,7 +74,7 @@ export default function umd( ? `${setupNamespace(options.name, 'global', true, options.globals, options.compact)}${_}=${_}` : ''; - const useStrict = options.strict !== false ? `${_}'use strict';${nl}` : ``; + const useStrict = options.strict !== false ? `${_}'use strict';${n}` : ``; let globalExport; @@ -85,42 +85,45 @@ export default function umd( factory = `var exports${_}=${_}factory(${globalDeps});`; } else if (namedExportsMode) { const module = globalDeps.shift(); - factory = `var exports${_}=${_}${module};${nl}`; + factory = `var exports${_}=${_}${module};${n}`; factory += `${t}${t}factory(${['exports'].concat(globalDeps)});`; } - globalExport = `(function()${_}{${nl}`; - globalExport += `${t}${t}var current${_}=${_}${safeAccess( - options.name, - options.compact - )};${nl}`; - globalExport += `${t}${t}${factory}${nl}`; - globalExport += `${t}${t}${globalProp(options.name)}${_}=${_}exports;${nl}`; + globalExport = `(function()${_}{${n}`; + globalExport += `${t}${t}var current${_}=${_}${safeAccess(options.name, options.compact)};${n}`; + globalExport += `${t}${t}${factory}${n}`; + globalExport += `${t}${t}${globalProp(options.name)}${_}=${_}exports;${n}`; globalExport += `${t}${t}exports.noConflict${_}=${_}function()${_}{${_}`; globalExport += `${globalProp(options.name)}${_}=${_}current;${_}return exports${ options.compact ? '' : '; ' - }};${nl}`; + }};${n}`; globalExport += `${t}})()`; } else { globalExport = `(${defaultExport}factory(${globalDeps}))`; } - let wrapperIntro = `(function${_}(global,${_}factory)${_}{${nl}`; + let wrapperIntro = `(function${_}(global,${_}factory)${_}{${n}`; wrapperIntro += `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?`; - wrapperIntro += `${_}${cjsExport}factory(${cjsDeps.join(`,${_}`)})${_}:${nl}`; - wrapperIntro += `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}factory)${_}:${nl}`; - wrapperIntro += `${t}${globalExport};${nl}`; - wrapperIntro += `}(this,${_}(function${_}(${args})${_}{${useStrict}${nl}`; + wrapperIntro += `${_}${cjsExport}factory(${cjsDeps.join(`,${_}`)})${_}:${n}`; + wrapperIntro += `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}factory)${_}:${n}`; + wrapperIntro += `${t}${globalExport};${n}`; + wrapperIntro += `}(this,${_}(function${_}(${args})${_}{${useStrict}${n}`; // var foo__default = 'default' in foo ? foo['default'] : foo; const interopBlock = getInteropBlock(dependencies, options, graph.varOrConst); - if (interopBlock) magicString.prepend(interopBlock + nl + nl); + if (interopBlock) magicString.prepend(interopBlock + n + n); if (intro) magicString.prepend(intro); - const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact); - if (exportBlock) magicString.append(nl + nl + exportBlock); + const exportBlock = getExportBlock( + exports, + dependencies, + namedExportsMode, + options.interop, + options.compact + ); + if (exportBlock) magicString.append(n + n + exportBlock); if (namedExportsMode && hasExports && options.legacy !== true) - magicString.append(nl + nl + (options.compact ? compactEsModuleExport : esModuleExport)); + magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport)); if (outro) magicString.append(outro); return magicString diff --git a/src/utils/addons.ts b/src/utils/addons.ts index 1ca07275035..a3e3924ad5e 100644 --- a/src/utils/addons.ts +++ b/src/utils/addons.ts @@ -14,14 +14,17 @@ export interface Addons { export function createAddons(graph: Graph, options: OutputOptions): Promise { return Promise.all([ - collectAddon(graph, options.banner, 'banner'), - collectAddon(graph, options.footer, 'footer'), + collectAddon(graph, options.banner, 'banner', '\n'), + collectAddon(graph, options.footer, 'footer', '\n'), collectAddon(graph, options.intro, 'intro', '\n\n'), collectAddon(graph, options.outro, 'outro', '\n\n') ]).then(([banner, footer, intro, outro]) => { if (intro) intro += '\n\n'; if (outro) outro = `\n\n${outro}`; + if (banner.length) banner += '\n'; + if (footer.length) footer = '\n' + footer; + const hash = new Uint8Array(4); return { intro, outro, banner, footer, hash }; @@ -32,7 +35,7 @@ function collectAddon( graph: Graph, initialAddon: string, addonName: 'banner' | 'footer' | 'intro' | 'outro', - sep: string = '\n' + sep: string ) { return runSequence( [ diff --git a/test/form/samples/compact/_config.js b/test/form/samples/compact/_config.js index 33df6b58cfc..870f5f3a0d0 100644 --- a/test/form/samples/compact/_config.js +++ b/test/form/samples/compact/_config.js @@ -3,7 +3,8 @@ module.exports = { options: { output: { name: 'foo', - compact: true + compact: true, + namespaceToStringTag: true } } }; diff --git a/test/form/samples/compact/_expected/amd.js b/test/form/samples/compact/_expected/amd.js index 25f26840c75..8a7afb86cfb 100644 --- a/test/form/samples/compact/_expected/amd.js +++ b/test/form/samples/compact/_expected/amd.js @@ -1,3 +1,4 @@ -define(['external'],function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { +define(['external'],function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +function foo$$1 () { console.log( x ); -}return foo;}); \ No newline at end of file +}return foo$$1;}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/cjs.js b/test/form/samples/compact/_expected/cjs.js index 9a24b7daab5..326f88c874a 100644 --- a/test/form/samples/compact/_expected/cjs.js +++ b/test/form/samples/compact/_expected/cjs.js @@ -1,3 +1,4 @@ -'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}var x=_interopDefault(require('external'));function foo () { +'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}var x=_interopDefault(require('external'));var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +function foo$$1 () { console.log( x ); -}module.exports=foo; \ No newline at end of file +}module.exports=foo$$1; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/es.js b/test/form/samples/compact/_expected/es.js index 29c61ff9aea..4181cd3ae10 100644 --- a/test/form/samples/compact/_expected/es.js +++ b/test/form/samples/compact/_expected/es.js @@ -1,3 +1,4 @@ -import x from'external';function foo () { +import x from'external';var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +function foo$$1 () { console.log( x ); -}export default foo; \ No newline at end of file +}export default foo$$1; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/iife.js b/test/form/samples/compact/_expected/iife.js index 2ffdc56edae..aa916c0a1d8 100644 --- a/test/form/samples/compact/_expected/iife.js +++ b/test/form/samples/compact/_expected/iife.js @@ -1,3 +1,4 @@ -var foo=(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { +var foo=(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +function foo$$1 () { console.log( x ); -}return foo;}(x)); \ No newline at end of file +}return foo$$1;}(x)); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/system.js b/test/form/samples/compact/_expected/system.js index 204b1a63e63..15277b0fe9b 100644 --- a/test/form/samples/compact/_expected/system.js +++ b/test/form/samples/compact/_expected/system.js @@ -1,3 +1,4 @@ -System.register(['external'],function(exports,module){'use strict';var x;return{setters:[function(module){x=module.default;}],execute:function(){exports('default',foo);function foo () { +System.register(['external'],function(exports,module){'use strict';var x;return{setters:[function(module){x=module.default;}],execute:function(){exports('default',foo$$1);var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +function foo$$1 () { console.log( x ); }}};}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/umd.js b/test/form/samples/compact/_expected/umd.js index ff35a37b4c3..8f4be54b80f 100644 --- a/test/form/samples/compact/_expected/umd.js +++ b/test/form/samples/compact/_expected/umd.js @@ -1,3 +1,4 @@ -(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory(require('external')):typeof define==='function'&&define.amd?define(['external'],factory):(global.foo=factory(global.x));}(this,(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;function foo () { +(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory(require('external')):typeof define==='function'&&define.amd?define(['external'],factory):(global.foo=factory(global.x));}(this,(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +function foo$$1 () { console.log( x ); -}return foo;}))); \ No newline at end of file +}return foo$$1;}))); \ No newline at end of file diff --git a/test/form/samples/compact/main.js b/test/form/samples/compact/main.js index 58ad4ee00c3..7b07ac67eef 100644 --- a/test/form/samples/compact/main.js +++ b/test/form/samples/compact/main.js @@ -1,4 +1,6 @@ import x from 'external'; +import * as self from './main.js'; +console.log(self); export default function foo () { console.log( x ); } From 7d427626e7bc084d441008d7de05061c9029cf8f Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Sun, 13 May 2018 20:33:13 +0200 Subject: [PATCH 10/14] compact feedback --- src/Chunk.ts | 5 +++- src/ast/nodes/Import.ts | 3 +++ src/ast/variables/NamespaceVariable.ts | 4 ++-- src/finalisers/system.ts | 2 +- .../_expected/system/chunk-ad0e6b97.js | 2 +- .../_expected/system/main1.js | 2 +- .../_expected/system/main2.js | 2 +- test/form/samples/compact/_expected/amd.js | 6 +++-- test/form/samples/compact/_expected/cjs.js | 6 +++-- test/form/samples/compact/_expected/es.js | 6 +++-- test/form/samples/compact/_expected/iife.js | 6 +++-- test/form/samples/compact/_expected/system.js | 6 +++-- test/form/samples/compact/_expected/umd.js | 6 +++-- test/form/samples/compact/main.js | 1 + test/function/samples/compact/_config.js | 23 +++++++++++++++++++ test/function/samples/compact/main.js | 10 ++++++++ 16 files changed, 71 insertions(+), 19 deletions(-) create mode 100644 test/function/samples/compact/_config.js create mode 100644 test/function/samples/compact/main.js diff --git a/src/Chunk.ts b/src/Chunk.ts index 3ffc97ebc96..342bf3ab770 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -776,6 +776,7 @@ export default class Chunk { for (const module of this.orderedModules) { const source = module.render(renderOptions); source.trim(); + if (options.compact && source.lastLine().indexOf('//') !== -1) source.append('\n'); this.renderedModuleSources.push(source); const namespace = module.getOrCreateNamespace(); @@ -793,7 +794,8 @@ export default class Chunk { if (hoistedSource) magicString.prepend(hoistedSource + n + n); - this.renderedSource = magicString.trim(); + this.renderedSource = options.compact ? magicString : magicString.trim(); + this.renderedSourceLength = undefined; this.renderedHash = undefined; @@ -1064,6 +1066,7 @@ export default class Chunk { } if (options.compact !== true && code[code.length - 1] !== '\n') code += '\n'; + return { code, map }; } ); diff --git a/src/ast/nodes/Import.ts b/src/ast/nodes/Import.ts index a2e1688852f..916f323eef3 100644 --- a/src/ast/nodes/Import.ts +++ b/src/ast/nodes/Import.ts @@ -64,6 +64,9 @@ export default class Import extends NodeBase { } render(code: MagicString, options: RenderOptions) { + const _ = options.compact ? '' : ' '; + const s = options.compact ? '' : ';'; + this.rendered = true; if (this.resolutionNamespace) { const _ = options.compact ? '' : ' '; diff --git a/src/ast/variables/NamespaceVariable.ts b/src/ast/variables/NamespaceVariable.ts index edc5322d8c2..9d48f7a7e45 100644 --- a/src/ast/variables/NamespaceVariable.ts +++ b/src/ast/variables/NamespaceVariable.ts @@ -55,7 +55,7 @@ export default class NamespaceVariable extends Variable { const original = this.originals[name]; if ((this.referencedEarly || original.isReassigned) && !options.legacy) { - return `${t}get ${name}${_}()${_}{${_}return${_}${original.getName()}${ + return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${ options.compact ? '' : ';' }${_}}`; } @@ -79,7 +79,7 @@ export default class NamespaceVariable extends Variable { if (options.namespaceToStringTag) { output += `${n}if${_}(typeof Symbol${_}!==${_}'undefined'${_}&&${_}Symbol.toStringTag)${n}`; output += `${t}Object.defineProperty(${name},${_}Symbol.toStringTag,${_}{${_}value:${_}'Module'${_}});${n}`; - output += `else${n}`; + output += `else${n || ' '}`; output += `${t}Object.defineProperty(${name},${_}'toString',${_}{${_}value:${_}function${_}()${_}{${_}return${_}'[object Module]'${ options.compact ? ';' : '' }${_}}${_}});${n}`; diff --git a/src/finalisers/system.ts b/src/finalisers/system.ts index 1699e422f59..90601024639 100644 --- a/src/finalisers/system.ts +++ b/src/finalisers/system.ts @@ -138,6 +138,6 @@ export default function system( return magicString .indent(`${t}${t}${t}`) - .append(`${n}${n}${t}${t}}${n}${t}};${n}});`) + .append(`${n}${n}${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`) .prepend(wrapperStart); } diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js index 18b08415474..9cbeaf02c46 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js @@ -3,4 +3,4 @@ System.register([],function(exports,module){'use strict';return{execute:function }function fn$1 () { fn(); console.log('dep2 fn'); -}}};}); \ No newline at end of file +}}}}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main1.js b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js index 1b5dd7f4132..94c4c4d13d8 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js @@ -5,4 +5,4 @@ System.register(['./chunk-ad0e6b97.js'],function(exports,module){'use strict';va fn$1(); fn(); } -} exports('default', Main1);}};}); \ No newline at end of file +} exports('default', Main1);}}}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main2.js b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js index 6eab9d175f2..f5101c2929d 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js @@ -9,4 +9,4 @@ System.register(['external','./chunk-ad0e6b97.js'],function(exports,module){'use fn$3(); fn$1(); } -} exports('default', Main2);}};}); \ No newline at end of file +} exports('default', Main2);}}}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/amd.js b/test/form/samples/compact/_expected/amd.js index 8a7afb86cfb..99d0972df45 100644 --- a/test/form/samples/compact/_expected/amd.js +++ b/test/form/samples/compact/_expected/amd.js @@ -1,4 +1,6 @@ -define(['external'],function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +define(['external'],function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); function foo$$1 () { console.log( x ); -}return foo$$1;}); \ No newline at end of file +} +// trailing comment +return foo$$1;}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/cjs.js b/test/form/samples/compact/_expected/cjs.js index 326f88c874a..9879460689f 100644 --- a/test/form/samples/compact/_expected/cjs.js +++ b/test/form/samples/compact/_expected/cjs.js @@ -1,4 +1,6 @@ -'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}var x=_interopDefault(require('external'));var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +'use strict';function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}var x=_interopDefault(require('external'));var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); function foo$$1 () { console.log( x ); -}module.exports=foo$$1; \ No newline at end of file +} +// trailing comment +module.exports=foo$$1; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/es.js b/test/form/samples/compact/_expected/es.js index 4181cd3ae10..8f810503d10 100644 --- a/test/form/samples/compact/_expected/es.js +++ b/test/form/samples/compact/_expected/es.js @@ -1,4 +1,6 @@ -import x from'external';var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +import x from'external';var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); function foo$$1 () { console.log( x ); -}export default foo$$1; \ No newline at end of file +} +// trailing comment +export default foo$$1; \ No newline at end of file diff --git a/test/form/samples/compact/_expected/iife.js b/test/form/samples/compact/_expected/iife.js index aa916c0a1d8..3f2bf173d83 100644 --- a/test/form/samples/compact/_expected/iife.js +++ b/test/form/samples/compact/_expected/iife.js @@ -1,4 +1,6 @@ -var foo=(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +var foo=(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); function foo$$1 () { console.log( x ); -}return foo$$1;}(x)); \ No newline at end of file +} +// trailing comment +return foo$$1;}(x)); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/system.js b/test/form/samples/compact/_expected/system.js index 15277b0fe9b..f79ffc31a94 100644 --- a/test/form/samples/compact/_expected/system.js +++ b/test/form/samples/compact/_expected/system.js @@ -1,4 +1,6 @@ -System.register(['external'],function(exports,module){'use strict';var x;return{setters:[function(module){x=module.default;}],execute:function(){exports('default',foo$$1);var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +System.register(['external'],function(exports,module){'use strict';var x;return{setters:[function(module){x=module.default;}],execute:function(){exports('default',foo$$1);var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); function foo$$1 () { console.log( x ); -}}};}); \ No newline at end of file +} +// trailing comment +}}}); \ No newline at end of file diff --git a/test/form/samples/compact/_expected/umd.js b/test/form/samples/compact/_expected/umd.js index 8f4be54b80f..26da37cc20f 100644 --- a/test/form/samples/compact/_expected/umd.js +++ b/test/form/samples/compact/_expected/umd.js @@ -1,4 +1,6 @@ -(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory(require('external')):typeof define==='function'&&define.amd?define(['external'],factory):(global.foo=factory(global.x));}(this,(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){returnfoo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});elseObject.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory(require('external')):typeof define==='function'&&define.amd?define(['external'],factory):(global.foo=factory(global.x));}(this,(function(x){'use strict';x=x&&x.hasOwnProperty('default')?x['default']:x;var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); function foo$$1 () { console.log( x ); -}return foo$$1;}))); \ No newline at end of file +} +// trailing comment +return foo$$1;}))); \ No newline at end of file diff --git a/test/form/samples/compact/main.js b/test/form/samples/compact/main.js index 7b07ac67eef..a6eb91ae5bb 100644 --- a/test/form/samples/compact/main.js +++ b/test/form/samples/compact/main.js @@ -4,3 +4,4 @@ console.log(self); export default function foo () { console.log( x ); } +// trailing comment \ No newline at end of file diff --git a/test/function/samples/compact/_config.js b/test/function/samples/compact/_config.js new file mode 100644 index 00000000000..4d4fda2dbb4 --- /dev/null +++ b/test/function/samples/compact/_config.js @@ -0,0 +1,23 @@ +module.exports = { + description: 'compact output with compact: true', + options: { + external: ['external'], + experimentalDynamicImport: true + }, + bundleOptions: { + compact: true, + namespaceToStringTag: true + }, + warnings: [ + { + code: 'CIRCULAR_DEPENDENCY', + importer: 'main.js', + message: 'Circular dependency: main.js -> main.js' + } + ], + context: { + require (x) { + return 42; + } + } +}; diff --git a/test/function/samples/compact/main.js b/test/function/samples/compact/main.js new file mode 100644 index 00000000000..ddf1540dac9 --- /dev/null +++ b/test/function/samples/compact/main.js @@ -0,0 +1,10 @@ +import x from 'external'; +import * as self from './main.js'; +console.log(self && self['de' + 'fault']); +export default function foo () { + console.log( x ); +} + +import('./main.js').then(self => { + console.log(self && sel['de' + 'fault']); +}); From 0e65beca16c8b75a7770fd8e1c46c903f6cdfee7 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Mon, 14 May 2018 11:22:16 +0200 Subject: [PATCH 11/14] ensure semicolon between compact sources --- src/Chunk.ts | 11 +++++++++-- .../amd/{chunk-1e9855f7.js => chunk-f4daa162.js} | 4 ++-- .../samples/chunking-compact/_expected/amd/main1.js | 6 +++--- .../samples/chunking-compact/_expected/amd/main2.js | 8 ++++---- .../cjs/{chunk-992f09ca.js => chunk-f7718a2e.js} | 4 ++-- .../samples/chunking-compact/_expected/cjs/main1.js | 6 +++--- .../samples/chunking-compact/_expected/cjs/main2.js | 8 ++++---- .../es/{chunk-5b60a9d9.js => chunk-f92a9406.js} | 4 ++-- .../samples/chunking-compact/_expected/es/main1.js | 6 +++--- .../samples/chunking-compact/_expected/es/main2.js | 8 ++++---- .../system/{chunk-ad0e6b97.js => chunk-d9826910.js} | 4 ++-- .../chunking-compact/_expected/system/main1.js | 4 ++-- .../chunking-compact/_expected/system/main2.js | 6 +++--- 13 files changed, 43 insertions(+), 36 deletions(-) rename test/chunking-form/samples/chunking-compact/_expected/amd/{chunk-1e9855f7.js => chunk-f4daa162.js} (75%) rename test/chunking-form/samples/chunking-compact/_expected/cjs/{chunk-992f09ca.js => chunk-f7718a2e.js} (70%) rename test/chunking-form/samples/chunking-compact/_expected/es/{chunk-5b60a9d9.js => chunk-f92a9406.js} (65%) rename test/chunking-form/samples/chunking-compact/_expected/system/{chunk-ad0e6b97.js => chunk-d9826910.js} (86%) diff --git a/src/Chunk.ts b/src/Chunk.ts index 342bf3ab770..54d0789bc3f 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -776,7 +776,10 @@ export default class Chunk { for (const module of this.orderedModules) { const source = module.render(renderOptions); source.trim(); - if (options.compact && source.lastLine().indexOf('//') !== -1) source.append('\n'); + if (options.compact) { + if (source.lastLine().indexOf('//') !== -1) source.append('\n'); + else if (source.lastChar() !== ';') source.append(';'); + } this.renderedModuleSources.push(source); const namespace = module.getOrCreateNamespace(); @@ -794,7 +797,11 @@ export default class Chunk { if (hoistedSource) magicString.prepend(hoistedSource + n + n); - this.renderedSource = options.compact ? magicString : magicString.trim(); + if (options.compact) { + this.renderedSource = magicString; + } else { + this.renderedSource = magicString.trim(); + } this.renderedSourceLength = undefined; this.renderedHash = undefined; diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js b/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-f4daa162.js similarity index 75% rename from test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js rename to test/chunking-form/samples/chunking-compact/_expected/amd/chunk-f4daa162.js index f793b3c38f3..35fe03758d0 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-f4daa162.js @@ -1,6 +1,6 @@ define(['exports'],function(exports){'use strict';function fn () { console.log('lib2 fn'); -}function fn$1 () { +};function fn$1 () { fn(); console.log('dep2 fn'); -}exports.a=fn$1;}); \ No newline at end of file +};exports.a=fn$1;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js b/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js index 3e115fe9f2e..288b6fdff75 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js @@ -1,8 +1,8 @@ -define(['./chunk-1e9855f7.js'],function(__chunk_1){'use strict';function fn () { +define(['./chunk-f4daa162.js'],function(__chunk_1){'use strict';function fn () { console.log('dep1 fn'); -}class Main1 { +};class Main1 { constructor () { fn(); __chunk_1.a(); } -}return Main1;}); \ No newline at end of file +};return Main1;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js b/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js index 42ff9bbd118..89581898005 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js @@ -1,12 +1,12 @@ -define(['external','./chunk-1e9855f7.js'],function(external,__chunk_1){'use strict';function fn () { +define(['external','./chunk-f4daa162.js'],function(external,__chunk_1){'use strict';function fn () { console.log('lib1 fn'); external.fn(); -}function fn$1 () { +};function fn$1 () { fn(); console.log('dep3 fn'); -}class Main2 { +};class Main2 { constructor () { fn$1(); __chunk_1.a(); } -}return Main2;}); \ No newline at end of file +};return Main2;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-f7718a2e.js similarity index 70% rename from test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js rename to test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-f7718a2e.js index 36b2112ae76..82cf102a7ec 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-f7718a2e.js @@ -1,6 +1,6 @@ 'use strict';function fn () { console.log('lib2 fn'); -}function fn$1 () { +};function fn$1 () { fn(); console.log('dep2 fn'); -}exports.a=fn$1; \ No newline at end of file +};exports.a=fn$1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js index 43df57fd5e6..f209b2fd572 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js @@ -1,8 +1,8 @@ -'use strict';var __chunk_1=require('./chunk-992f09ca.js');function fn () { +'use strict';var __chunk_1=require('./chunk-f7718a2e.js');function fn () { console.log('dep1 fn'); -}class Main1 { +};class Main1 { constructor () { fn(); __chunk_1.a(); } -}module.exports=Main1; \ No newline at end of file +};module.exports=Main1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js index ef8939f2eb3..e7198b3fdd0 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js @@ -1,12 +1,12 @@ -'use strict';var external=require('external'),__chunk_1=require('./chunk-992f09ca.js');function fn () { +'use strict';var external=require('external'),__chunk_1=require('./chunk-f7718a2e.js');function fn () { console.log('lib1 fn'); external.fn(); -}function fn$1 () { +};function fn$1 () { fn(); console.log('dep3 fn'); -}class Main2 { +};class Main2 { constructor () { fn$1(); __chunk_1.a(); } -}module.exports=Main2; \ No newline at end of file +};module.exports=Main2; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js b/test/chunking-form/samples/chunking-compact/_expected/es/chunk-f92a9406.js similarity index 65% rename from test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js rename to test/chunking-form/samples/chunking-compact/_expected/es/chunk-f92a9406.js index b8c1ff4df40..032a3caf6a4 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js +++ b/test/chunking-form/samples/chunking-compact/_expected/es/chunk-f92a9406.js @@ -1,6 +1,6 @@ function fn () { console.log('lib2 fn'); -}function fn$1 () { +};function fn$1 () { fn(); console.log('dep2 fn'); -}export{fn$1 as a}; \ No newline at end of file +};export{fn$1 as a}; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/main1.js b/test/chunking-form/samples/chunking-compact/_expected/es/main1.js index 0105d5c2a5f..c1322ed1ad7 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/es/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/es/main1.js @@ -1,8 +1,8 @@ -import {a as fn}from'./chunk-5b60a9d9.js';function fn$1 () { +import {a as fn}from'./chunk-f92a9406.js';function fn$1 () { console.log('dep1 fn'); -}class Main1 { +};class Main1 { constructor () { fn$1(); fn(); } -}export default Main1; \ No newline at end of file +};export default Main1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/main2.js b/test/chunking-form/samples/chunking-compact/_expected/es/main2.js index 6390ed6812d..54a91be72a9 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/es/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/es/main2.js @@ -1,12 +1,12 @@ -import {fn}from'external';import {a as fn$1}from'./chunk-5b60a9d9.js';function fn$2 () { +import {fn}from'external';import {a as fn$1}from'./chunk-f92a9406.js';function fn$2 () { console.log('lib1 fn'); fn(); -}function fn$3 () { +};function fn$3 () { fn$2(); console.log('dep3 fn'); -}class Main2 { +};class Main2 { constructor () { fn$3(); fn$1(); } -}export default Main2; \ No newline at end of file +};export default Main2; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-d9826910.js similarity index 86% rename from test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js rename to test/chunking-form/samples/chunking-compact/_expected/system/chunk-d9826910.js index 9cbeaf02c46..53e18f968ac 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-d9826910.js @@ -1,6 +1,6 @@ System.register([],function(exports,module){'use strict';return{execute:function(){exports('a',fn$1);function fn () { console.log('lib2 fn'); -}function fn$1 () { +};function fn$1 () { fn(); console.log('dep2 fn'); -}}}}); \ No newline at end of file +};}}}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main1.js b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js index 94c4c4d13d8..885ed87478a 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js @@ -1,6 +1,6 @@ -System.register(['./chunk-ad0e6b97.js'],function(exports,module){'use strict';var fn;return{setters:[function(module){fn=module.a;}],execute:function(){function fn$1 () { +System.register(['./chunk-d9826910.js'],function(exports,module){'use strict';var fn;return{setters:[function(module){fn=module.a;}],execute:function(){function fn$1 () { console.log('dep1 fn'); -}class Main1 { +};class Main1 { constructor () { fn$1(); fn(); diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main2.js b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js index f5101c2929d..e535eccf883 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js @@ -1,10 +1,10 @@ -System.register(['external','./chunk-ad0e6b97.js'],function(exports,module){'use strict';var fn,fn$1;return{setters:[function(module){fn=module.fn;},function(module){fn$1=module.a;}],execute:function(){function fn$2 () { +System.register(['external','./chunk-d9826910.js'],function(exports,module){'use strict';var fn,fn$1;return{setters:[function(module){fn=module.fn;},function(module){fn$1=module.a;}],execute:function(){function fn$2 () { console.log('lib1 fn'); fn(); -}function fn$3 () { +};function fn$3 () { fn$2(); console.log('dep3 fn'); -}class Main2 { +};class Main2 { constructor () { fn$3(); fn$1(); From a6d1978fecadfc7f40d0981cb7cfebad4e896593 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Mon, 14 May 2018 12:52:06 +0200 Subject: [PATCH 12/14] handling trailing module statement asi cases --- src/Chunk.ts | 8 ++--- src/Module.ts | 4 ++- src/ast/nodes/ExportDefaultDeclaration.ts | 8 ++++- src/ast/nodes/Program.ts | 36 ++++++++++++++++++- src/utils/renderHelpers.ts | 6 ++-- .../_expected/amd/main1alias.js | 2 +- ...ias-ad3b5af8.js => main2alias-bff49b9a.js} | 2 +- .../_expected/amd/main2alias.js | 2 +- .../_expected/cjs/main1alias.js | 2 +- ...ias-952c9a65.js => main2alias-4b102ef6.js} | 2 +- .../_expected/cjs/main2alias.js | 2 +- .../_expected/es/main1alias.js | 2 +- ...ias-de61dac0.js => main2alias-e628225d.js} | 2 +- .../_expected/es/main2alias.js | 2 +- .../_expected/system/main1alias.js | 2 +- ...ias-8bad9260.js => main2alias-4b538eea.js} | 2 +- .../_expected/system/main2alias.js | 2 +- test/form/samples/asi/_config.js | 3 ++ test/form/samples/asi/_expected.js | 5 +++ test/form/samples/asi/c.js | 1 + test/form/samples/asi/main.js | 4 +++ 21 files changed, 76 insertions(+), 23 deletions(-) rename test/chunking-form/samples/entrypoint-aliasing/_expected/amd/{main2alias-ad3b5af8.js => main2alias-bff49b9a.js} (88%) rename test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/{main2alias-952c9a65.js => main2alias-4b102ef6.js} (84%) rename test/chunking-form/samples/entrypoint-aliasing/_expected/es/{main2alias-de61dac0.js => main2alias-e628225d.js} (81%) rename test/chunking-form/samples/entrypoint-aliasing/_expected/system/{main2alias-8bad9260.js => main2alias-4b538eea.js} (85%) create mode 100644 test/form/samples/asi/_config.js create mode 100644 test/form/samples/asi/_expected.js create mode 100644 test/form/samples/asi/c.js create mode 100644 test/form/samples/asi/main.js diff --git a/src/Chunk.ts b/src/Chunk.ts index 54d0789bc3f..a917c800eee 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -773,13 +773,11 @@ export default class Chunk { this.renderedModuleSources = []; - for (const module of this.orderedModules) { + for (let i = 0; i < this.orderedModules.length; i++) { + const module = this.orderedModules[i]; const source = module.render(renderOptions); source.trim(); - if (options.compact) { - if (source.lastLine().indexOf('//') !== -1) source.append('\n'); - else if (source.lastChar() !== ';') source.append(';'); - } + if (options.compact && source.lastLine().indexOf('//') !== -1) source.append('\n'); this.renderedModuleSources.push(source); const namespace = module.getOrCreateNamespace(); diff --git a/src/Module.ts b/src/Module.ts index 083bac23929..120c139cf79 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -15,7 +15,7 @@ import ImportSpecifier from './ast/nodes/ImportSpecifier'; import Graph from './Graph'; import Variable from './ast/variables/Variable'; import Program from './ast/nodes/Program'; -import { GenericEsTreeNode, Node, NodeBase } from './ast/nodes/shared/Node'; +import { GenericEsTreeNode, Node, NodeBase, StatementNode } from './ast/nodes/shared/Node'; import ExportNamedDeclaration from './ast/nodes/ExportNamedDeclaration'; import ImportDeclaration from './ast/nodes/ImportDeclaration'; import Identifier from './ast/nodes/Identifier'; @@ -35,6 +35,8 @@ import { isLiteral } from './ast/nodes/Literal'; import Chunk from './Chunk'; import { RenderOptions } from './utils/renderHelpers'; import { getOriginalLocation } from './utils/getOriginalLocation'; +import VariableDeclaration from './ast/nodes/VariableDeclaration'; +import ExpressionStatement from './ast/nodes/ExpressionStatement'; export interface CommentDescription { block: boolean; diff --git a/src/ast/nodes/ExportDefaultDeclaration.ts b/src/ast/nodes/ExportDefaultDeclaration.ts index 2e2f5398f7a..b3bc286fc29 100644 --- a/src/ast/nodes/ExportDefaultDeclaration.ts +++ b/src/ast/nodes/ExportDefaultDeclaration.ts @@ -157,8 +157,14 @@ export default class ExportDefaultDeclaration extends NodeBase { declarationStart, `${this.context.varOrConst} ${this.variable.getName()} = ${systemBinding}` ); + const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/ if (systemBinding) { - code.appendLeft(code.original[this.end - 1] === ';' ? this.end - 1 : this.end, ')'); + code.appendLeft( + hasTrailingSemicolon ? this.end - 1 : this.end, + ')' + (hasTrailingSemicolon ? '' : ';') + ); + } else if (!hasTrailingSemicolon) { + code.appendLeft(this.end, ';'); } } } diff --git a/src/ast/nodes/Program.ts b/src/ast/nodes/Program.ts index b05368cbc5a..c96846739a8 100644 --- a/src/ast/nodes/Program.ts +++ b/src/ast/nodes/Program.ts @@ -1,8 +1,10 @@ import MagicString from 'magic-string'; import { NodeBase, StatementNode } from './shared/Node'; import * as NodeType from './NodeType'; -import { RenderOptions, renderStatementList } from '../../utils/renderHelpers'; +import { RenderOptions, renderStatementList, findFirstLineBreakOutsideComment } from '../../utils/renderHelpers'; import { ExecutionPathOptions } from '../ExecutionPathOptions'; +import VariableDeclaration from './VariableDeclaration'; +import ExpressionStatement from './ExpressionStatement'; export default class Program extends NodeBase { type: NodeType.tProgram; @@ -25,6 +27,38 @@ export default class Program extends NodeBase { render(code: MagicString, options: RenderOptions) { if (this.body.length) { renderStatementList(this.body, code, this.start, this.end, options); + + let lastStatement: StatementNode; + for (let i = this.body.length - 1; i >= 0; i--) { + lastStatement = this.body[i]; + if (lastStatement.included) break; + } + if (lastStatement && code.original.charCodeAt(lastStatement.end - 1) !== 59 /*";"*/) { + const trailingNewline = + !options.compact || + findFirstLineBreakOutsideComment(code.original.slice(lastStatement.end)) !== -1; + // these rules can be refined over time + let needsSemicolon = false; + if (trailingNewline) { + if ( + lastStatement instanceof VariableDeclaration || + lastStatement instanceof ExpressionStatement + ) + needsSemicolon = true; + } else { + needsSemicolon = true; + } + + if (needsSemicolon) { + let alreadyRenderedSemicolon = false; + try { + alreadyRenderedSemicolon = code + .slice(lastStatement.end - 1, lastStatement.end) + .endsWith(';'); + } catch (e) {} + if (!alreadyRenderedSemicolon) code.appendLeft(lastStatement.end, ';'); + } + } } else { super.render(code, options); } diff --git a/src/utils/renderHelpers.ts b/src/utils/renderHelpers.ts index 37b6f0f2478..a31dfe3a247 100644 --- a/src/utils/renderHelpers.ts +++ b/src/utils/renderHelpers.ts @@ -1,4 +1,4 @@ -import { Node } from '../ast/nodes/shared/Node'; +import { Node, StatementNode } from '../ast/nodes/shared/Node'; import MagicString from 'magic-string'; export interface RenderOptions { @@ -48,7 +48,7 @@ export function findFirstOccurrenceOutsideComment( } } -function findFirstLineBreakOutsideComment(code: string, start: number = 0) { +export function findFirstLineBreakOutsideComment(code: string, start: number = 0) { let lineBreakPos, charCodeAfterSlash; lineBreakPos = code.indexOf('\n', start); while (true) { @@ -67,7 +67,7 @@ function findFirstLineBreakOutsideComment(code: string, start: number = 0) { } export function renderStatementList( - statements: Node[], + statements: StatementNode[], code: MagicString, start: number, end: number, diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main1alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main1alias.js index 7a018ba8417..5b06c7c1984 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main1alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main1alias.js @@ -1,4 +1,4 @@ -define(['./main2alias-ad3b5af8.js'], function (main2alias) { 'use strict'; +define(['./main2alias-bff49b9a.js'], function (main2alias) { 'use strict'; main2alias.log(main2alias.dep); diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias-ad3b5af8.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias-bff49b9a.js similarity index 88% rename from test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias-ad3b5af8.js rename to test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias-bff49b9a.js index 28ee2662a9b..4a5858c04a1 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias-ad3b5af8.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias-bff49b9a.js @@ -1,6 +1,6 @@ define(['exports'], function (exports) { 'use strict'; - var dep = { x: 42 } + var dep = { x: 42 }; function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias.js index 62b73008514..4dfb66362c7 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/amd/main2alias.js @@ -1,4 +1,4 @@ -define(['./main2alias-ad3b5af8.js'], function (main2alias) { 'use strict'; +define(['./main2alias-bff49b9a.js'], function (main2alias) { 'use strict'; diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main1alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main1alias.js index 9e4068f8d7b..3296cd10130 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main1alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main1alias.js @@ -1,5 +1,5 @@ 'use strict'; -var main2alias = require('./main2alias-952c9a65.js'); +var main2alias = require('./main2alias-4b102ef6.js'); main2alias.log(main2alias.dep); diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias-952c9a65.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias-4b102ef6.js similarity index 84% rename from test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias-952c9a65.js rename to test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias-4b102ef6.js index 4fd38570946..6c9f57c4580 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias-952c9a65.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias-4b102ef6.js @@ -1,6 +1,6 @@ 'use strict'; -var dep = { x: 42 } +var dep = { x: 42 }; function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias.js index 3621fe77195..d48818fa34b 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/cjs/main2alias.js @@ -1,6 +1,6 @@ 'use strict'; -var main2alias = require('./main2alias-952c9a65.js'); +var main2alias = require('./main2alias-4b102ef6.js'); diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main1alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main1alias.js index 73d25d3b154..2ad08eee135 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main1alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main1alias.js @@ -1,3 +1,3 @@ -import { a as dep, b as log } from './main2alias-de61dac0.js'; +import { a as dep, b as log } from './main2alias-e628225d.js'; log(dep); diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias-de61dac0.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias-e628225d.js similarity index 81% rename from test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias-de61dac0.js rename to test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias-e628225d.js index 573a56efce1..47f232a6b54 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias-de61dac0.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias-e628225d.js @@ -1,4 +1,4 @@ -var dep = { x: 42 } +var dep = { x: 42 }; function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias.js index f45f979d03b..78cbc35df20 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/es/main2alias.js @@ -1 +1 @@ -export { b as default } from './main2alias-de61dac0.js'; +export { b as default } from './main2alias-e628225d.js'; diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main1alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main1alias.js index 6cafcc0bc4f..4d76a17df7c 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main1alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main1alias.js @@ -1,4 +1,4 @@ -System.register(['./main2alias-8bad9260.js'], function (exports, module) { +System.register(['./main2alias-4b538eea.js'], function (exports, module) { 'use strict'; var dep, log; return { diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias-8bad9260.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias-4b538eea.js similarity index 85% rename from test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias-8bad9260.js rename to test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias-4b538eea.js index bee68d1b964..6ae34933c55 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias-8bad9260.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias-4b538eea.js @@ -4,7 +4,7 @@ System.register([], function (exports, module) { execute: function () { exports('b', log); - var dep = exports('a', { x: 42 }) + var dep = exports('a', { x: 42 }); function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias.js b/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias.js index eef2eb5d839..cfceaba2557 100644 --- a/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias.js +++ b/test/chunking-form/samples/entrypoint-aliasing/_expected/system/main2alias.js @@ -1,4 +1,4 @@ -System.register(['./main2alias-8bad9260.js'], function (exports, module) { +System.register(['./main2alias-4b538eea.js'], function (exports, module) { 'use strict'; return { setters: [function (module) { diff --git a/test/form/samples/asi/_config.js b/test/form/samples/asi/_config.js new file mode 100644 index 00000000000..f27e98a2fa0 --- /dev/null +++ b/test/form/samples/asi/_config.js @@ -0,0 +1,3 @@ +module.exports = { + description: 'Adds trailing semicolons for modules' +}; diff --git a/test/form/samples/asi/_expected.js b/test/form/samples/asi/_expected.js new file mode 100644 index 00000000000..d53d7b431bd --- /dev/null +++ b/test/form/samples/asi/_expected.js @@ -0,0 +1,5 @@ +var c = 0; + +(()=>{ + console.log(c); +})(); diff --git a/test/form/samples/asi/c.js b/test/form/samples/asi/c.js new file mode 100644 index 00000000000..19f0b517d7c --- /dev/null +++ b/test/form/samples/asi/c.js @@ -0,0 +1 @@ +export default 0 \ No newline at end of file diff --git a/test/form/samples/asi/main.js b/test/form/samples/asi/main.js new file mode 100644 index 00000000000..a1dc7711ff9 --- /dev/null +++ b/test/form/samples/asi/main.js @@ -0,0 +1,4 @@ +import c from './c.js' +;(()=>{ + console.log(c) +})() \ No newline at end of file From 03efe1074ccfbbbcc95b307696a5cab748851201 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Mon, 14 May 2018 12:57:25 +0200 Subject: [PATCH 13/14] simplify asi handling due to render delegations --- src/ast/nodes/Program.ts | 32 ------------------- .../{chunk-f4daa162.js => chunk-1e9855f7.js} | 4 +-- .../chunking-compact/_expected/amd/main1.js | 6 ++-- .../chunking-compact/_expected/amd/main2.js | 8 ++--- .../{chunk-f7718a2e.js => chunk-992f09ca.js} | 4 +-- .../chunking-compact/_expected/cjs/main1.js | 6 ++-- .../chunking-compact/_expected/cjs/main2.js | 8 ++--- .../{chunk-f92a9406.js => chunk-5b60a9d9.js} | 4 +-- .../chunking-compact/_expected/es/main1.js | 6 ++-- .../chunking-compact/_expected/es/main2.js | 8 ++--- .../{chunk-d9826910.js => chunk-ad0e6b97.js} | 4 +-- .../_expected/system/main1.js | 4 +-- .../_expected/system/main2.js | 6 ++-- .../entrypoint-facade/_expected/amd/main1.js | 2 +- .../{main2-ad3b5af8.js => main2-bff49b9a.js} | 2 +- .../entrypoint-facade/_expected/amd/main2.js | 2 +- .../entrypoint-facade/_expected/cjs/main1.js | 2 +- .../{main2-952c9a65.js => main2-4b102ef6.js} | 2 +- .../entrypoint-facade/_expected/cjs/main2.js | 2 +- .../entrypoint-facade/_expected/es/main1.js | 2 +- .../{main2-de61dac0.js => main2-e628225d.js} | 2 +- .../entrypoint-facade/_expected/es/main2.js | 2 +- .../_expected/system/main1.js | 2 +- .../{main2-8bad9260.js => main2-4b538eea.js} | 2 +- .../_expected/system/main2.js | 2 +- test/form/samples/{asi => asi-var}/_config.js | 0 .../samples/{asi => asi-var}/_expected.js | 0 test/form/samples/{asi => asi-var}/c.js | 0 test/form/samples/{asi => asi-var}/main.js | 0 29 files changed, 46 insertions(+), 78 deletions(-) rename test/chunking-form/samples/chunking-compact/_expected/amd/{chunk-f4daa162.js => chunk-1e9855f7.js} (75%) rename test/chunking-form/samples/chunking-compact/_expected/cjs/{chunk-f7718a2e.js => chunk-992f09ca.js} (70%) rename test/chunking-form/samples/chunking-compact/_expected/es/{chunk-f92a9406.js => chunk-5b60a9d9.js} (65%) rename test/chunking-form/samples/chunking-compact/_expected/system/{chunk-d9826910.js => chunk-ad0e6b97.js} (86%) rename test/chunking-form/samples/entrypoint-facade/_expected/amd/{main2-ad3b5af8.js => main2-bff49b9a.js} (88%) rename test/chunking-form/samples/entrypoint-facade/_expected/cjs/{main2-952c9a65.js => main2-4b102ef6.js} (84%) rename test/chunking-form/samples/entrypoint-facade/_expected/es/{main2-de61dac0.js => main2-e628225d.js} (81%) rename test/chunking-form/samples/entrypoint-facade/_expected/system/{main2-8bad9260.js => main2-4b538eea.js} (85%) rename test/form/samples/{asi => asi-var}/_config.js (100%) rename test/form/samples/{asi => asi-var}/_expected.js (100%) rename test/form/samples/{asi => asi-var}/c.js (100%) rename test/form/samples/{asi => asi-var}/main.js (100%) diff --git a/src/ast/nodes/Program.ts b/src/ast/nodes/Program.ts index c96846739a8..9aff6b27705 100644 --- a/src/ast/nodes/Program.ts +++ b/src/ast/nodes/Program.ts @@ -27,38 +27,6 @@ export default class Program extends NodeBase { render(code: MagicString, options: RenderOptions) { if (this.body.length) { renderStatementList(this.body, code, this.start, this.end, options); - - let lastStatement: StatementNode; - for (let i = this.body.length - 1; i >= 0; i--) { - lastStatement = this.body[i]; - if (lastStatement.included) break; - } - if (lastStatement && code.original.charCodeAt(lastStatement.end - 1) !== 59 /*";"*/) { - const trailingNewline = - !options.compact || - findFirstLineBreakOutsideComment(code.original.slice(lastStatement.end)) !== -1; - // these rules can be refined over time - let needsSemicolon = false; - if (trailingNewline) { - if ( - lastStatement instanceof VariableDeclaration || - lastStatement instanceof ExpressionStatement - ) - needsSemicolon = true; - } else { - needsSemicolon = true; - } - - if (needsSemicolon) { - let alreadyRenderedSemicolon = false; - try { - alreadyRenderedSemicolon = code - .slice(lastStatement.end - 1, lastStatement.end) - .endsWith(';'); - } catch (e) {} - if (!alreadyRenderedSemicolon) code.appendLeft(lastStatement.end, ';'); - } - } } else { super.render(code, options); } diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-f4daa162.js b/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js similarity index 75% rename from test/chunking-form/samples/chunking-compact/_expected/amd/chunk-f4daa162.js rename to test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js index 35fe03758d0..f793b3c38f3 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-f4daa162.js +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/chunk-1e9855f7.js @@ -1,6 +1,6 @@ define(['exports'],function(exports){'use strict';function fn () { console.log('lib2 fn'); -};function fn$1 () { +}function fn$1 () { fn(); console.log('dep2 fn'); -};exports.a=fn$1;}); \ No newline at end of file +}exports.a=fn$1;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js b/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js index 288b6fdff75..3e115fe9f2e 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/main1.js @@ -1,8 +1,8 @@ -define(['./chunk-f4daa162.js'],function(__chunk_1){'use strict';function fn () { +define(['./chunk-1e9855f7.js'],function(__chunk_1){'use strict';function fn () { console.log('dep1 fn'); -};class Main1 { +}class Main1 { constructor () { fn(); __chunk_1.a(); } -};return Main1;}); \ No newline at end of file +}return Main1;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js b/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js index 89581898005..42ff9bbd118 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/amd/main2.js @@ -1,12 +1,12 @@ -define(['external','./chunk-f4daa162.js'],function(external,__chunk_1){'use strict';function fn () { +define(['external','./chunk-1e9855f7.js'],function(external,__chunk_1){'use strict';function fn () { console.log('lib1 fn'); external.fn(); -};function fn$1 () { +}function fn$1 () { fn(); console.log('dep3 fn'); -};class Main2 { +}class Main2 { constructor () { fn$1(); __chunk_1.a(); } -};return Main2;}); \ No newline at end of file +}return Main2;}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-f7718a2e.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js similarity index 70% rename from test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-f7718a2e.js rename to test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js index 82cf102a7ec..36b2112ae76 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-f7718a2e.js +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/chunk-992f09ca.js @@ -1,6 +1,6 @@ 'use strict';function fn () { console.log('lib2 fn'); -};function fn$1 () { +}function fn$1 () { fn(); console.log('dep2 fn'); -};exports.a=fn$1; \ No newline at end of file +}exports.a=fn$1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js index f209b2fd572..43df57fd5e6 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/main1.js @@ -1,8 +1,8 @@ -'use strict';var __chunk_1=require('./chunk-f7718a2e.js');function fn () { +'use strict';var __chunk_1=require('./chunk-992f09ca.js');function fn () { console.log('dep1 fn'); -};class Main1 { +}class Main1 { constructor () { fn(); __chunk_1.a(); } -};module.exports=Main1; \ No newline at end of file +}module.exports=Main1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js b/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js index e7198b3fdd0..ef8939f2eb3 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/cjs/main2.js @@ -1,12 +1,12 @@ -'use strict';var external=require('external'),__chunk_1=require('./chunk-f7718a2e.js');function fn () { +'use strict';var external=require('external'),__chunk_1=require('./chunk-992f09ca.js');function fn () { console.log('lib1 fn'); external.fn(); -};function fn$1 () { +}function fn$1 () { fn(); console.log('dep3 fn'); -};class Main2 { +}class Main2 { constructor () { fn$1(); __chunk_1.a(); } -};module.exports=Main2; \ No newline at end of file +}module.exports=Main2; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/chunk-f92a9406.js b/test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js similarity index 65% rename from test/chunking-form/samples/chunking-compact/_expected/es/chunk-f92a9406.js rename to test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js index 032a3caf6a4..b8c1ff4df40 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/es/chunk-f92a9406.js +++ b/test/chunking-form/samples/chunking-compact/_expected/es/chunk-5b60a9d9.js @@ -1,6 +1,6 @@ function fn () { console.log('lib2 fn'); -};function fn$1 () { +}function fn$1 () { fn(); console.log('dep2 fn'); -};export{fn$1 as a}; \ No newline at end of file +}export{fn$1 as a}; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/main1.js b/test/chunking-form/samples/chunking-compact/_expected/es/main1.js index c1322ed1ad7..0105d5c2a5f 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/es/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/es/main1.js @@ -1,8 +1,8 @@ -import {a as fn}from'./chunk-f92a9406.js';function fn$1 () { +import {a as fn}from'./chunk-5b60a9d9.js';function fn$1 () { console.log('dep1 fn'); -};class Main1 { +}class Main1 { constructor () { fn$1(); fn(); } -};export default Main1; \ No newline at end of file +}export default Main1; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/es/main2.js b/test/chunking-form/samples/chunking-compact/_expected/es/main2.js index 54a91be72a9..6390ed6812d 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/es/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/es/main2.js @@ -1,12 +1,12 @@ -import {fn}from'external';import {a as fn$1}from'./chunk-f92a9406.js';function fn$2 () { +import {fn}from'external';import {a as fn$1}from'./chunk-5b60a9d9.js';function fn$2 () { console.log('lib1 fn'); fn(); -};function fn$3 () { +}function fn$3 () { fn$2(); console.log('dep3 fn'); -};class Main2 { +}class Main2 { constructor () { fn$3(); fn$1(); } -};export default Main2; \ No newline at end of file +}export default Main2; \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/chunk-d9826910.js b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js similarity index 86% rename from test/chunking-form/samples/chunking-compact/_expected/system/chunk-d9826910.js rename to test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js index 53e18f968ac..9cbeaf02c46 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/chunk-d9826910.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/chunk-ad0e6b97.js @@ -1,6 +1,6 @@ System.register([],function(exports,module){'use strict';return{execute:function(){exports('a',fn$1);function fn () { console.log('lib2 fn'); -};function fn$1 () { +}function fn$1 () { fn(); console.log('dep2 fn'); -};}}}); \ No newline at end of file +}}}}); \ No newline at end of file diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main1.js b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js index 885ed87478a..94c4c4d13d8 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/main1.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main1.js @@ -1,6 +1,6 @@ -System.register(['./chunk-d9826910.js'],function(exports,module){'use strict';var fn;return{setters:[function(module){fn=module.a;}],execute:function(){function fn$1 () { +System.register(['./chunk-ad0e6b97.js'],function(exports,module){'use strict';var fn;return{setters:[function(module){fn=module.a;}],execute:function(){function fn$1 () { console.log('dep1 fn'); -};class Main1 { +}class Main1 { constructor () { fn$1(); fn(); diff --git a/test/chunking-form/samples/chunking-compact/_expected/system/main2.js b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js index e535eccf883..f5101c2929d 100644 --- a/test/chunking-form/samples/chunking-compact/_expected/system/main2.js +++ b/test/chunking-form/samples/chunking-compact/_expected/system/main2.js @@ -1,10 +1,10 @@ -System.register(['external','./chunk-d9826910.js'],function(exports,module){'use strict';var fn,fn$1;return{setters:[function(module){fn=module.fn;},function(module){fn$1=module.a;}],execute:function(){function fn$2 () { +System.register(['external','./chunk-ad0e6b97.js'],function(exports,module){'use strict';var fn,fn$1;return{setters:[function(module){fn=module.fn;},function(module){fn$1=module.a;}],execute:function(){function fn$2 () { console.log('lib1 fn'); fn(); -};function fn$3 () { +}function fn$3 () { fn$2(); console.log('dep3 fn'); -};class Main2 { +}class Main2 { constructor () { fn$3(); fn$1(); diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/amd/main1.js b/test/chunking-form/samples/entrypoint-facade/_expected/amd/main1.js index 7ce96d0b2cd..081937446b7 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/amd/main1.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/amd/main1.js @@ -1,4 +1,4 @@ -define(['./main2-ad3b5af8.js'], function (main2) { 'use strict'; +define(['./main2-bff49b9a.js'], function (main2) { 'use strict'; main2.log(main2.dep); diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2-ad3b5af8.js b/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2-bff49b9a.js similarity index 88% rename from test/chunking-form/samples/entrypoint-facade/_expected/amd/main2-ad3b5af8.js rename to test/chunking-form/samples/entrypoint-facade/_expected/amd/main2-bff49b9a.js index 28ee2662a9b..4a5858c04a1 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2-ad3b5af8.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2-bff49b9a.js @@ -1,6 +1,6 @@ define(['exports'], function (exports) { 'use strict'; - var dep = { x: 42 } + var dep = { x: 42 }; function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2.js b/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2.js index 7f4be50eeeb..3be44aecde9 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/amd/main2.js @@ -1,4 +1,4 @@ -define(['./main2-ad3b5af8.js'], function (main2) { 'use strict'; +define(['./main2-bff49b9a.js'], function (main2) { 'use strict'; diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main1.js b/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main1.js index a4b0a705938..6daf01b3e63 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main1.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main1.js @@ -1,5 +1,5 @@ 'use strict'; -var main2 = require('./main2-952c9a65.js'); +var main2 = require('./main2-4b102ef6.js'); main2.log(main2.dep); diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2-952c9a65.js b/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2-4b102ef6.js similarity index 84% rename from test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2-952c9a65.js rename to test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2-4b102ef6.js index 4fd38570946..6c9f57c4580 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2-952c9a65.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2-4b102ef6.js @@ -1,6 +1,6 @@ 'use strict'; -var dep = { x: 42 } +var dep = { x: 42 }; function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2.js b/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2.js index 5b41193f774..6ed7464308a 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/cjs/main2.js @@ -1,6 +1,6 @@ 'use strict'; -var main2 = require('./main2-952c9a65.js'); +var main2 = require('./main2-4b102ef6.js'); diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/es/main1.js b/test/chunking-form/samples/entrypoint-facade/_expected/es/main1.js index 5a33fdb898f..97ce6a66ac9 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/es/main1.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/es/main1.js @@ -1,3 +1,3 @@ -import { a as dep, b as log } from './main2-de61dac0.js'; +import { a as dep, b as log } from './main2-e628225d.js'; log(dep); diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/es/main2-de61dac0.js b/test/chunking-form/samples/entrypoint-facade/_expected/es/main2-e628225d.js similarity index 81% rename from test/chunking-form/samples/entrypoint-facade/_expected/es/main2-de61dac0.js rename to test/chunking-form/samples/entrypoint-facade/_expected/es/main2-e628225d.js index 573a56efce1..47f232a6b54 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/es/main2-de61dac0.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/es/main2-e628225d.js @@ -1,4 +1,4 @@ -var dep = { x: 42 } +var dep = { x: 42 }; function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/es/main2.js b/test/chunking-form/samples/entrypoint-facade/_expected/es/main2.js index 0abce33274c..916361ee016 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/es/main2.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/es/main2.js @@ -1 +1 @@ -export { b as default } from './main2-de61dac0.js'; +export { b as default } from './main2-e628225d.js'; diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/system/main1.js b/test/chunking-form/samples/entrypoint-facade/_expected/system/main1.js index c5c4bba3952..008f4f04336 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/system/main1.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/system/main1.js @@ -1,4 +1,4 @@ -System.register(['./main2-8bad9260.js'], function (exports, module) { +System.register(['./main2-4b538eea.js'], function (exports, module) { 'use strict'; var dep, log; return { diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/system/main2-8bad9260.js b/test/chunking-form/samples/entrypoint-facade/_expected/system/main2-4b538eea.js similarity index 85% rename from test/chunking-form/samples/entrypoint-facade/_expected/system/main2-8bad9260.js rename to test/chunking-form/samples/entrypoint-facade/_expected/system/main2-4b538eea.js index bee68d1b964..6ae34933c55 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/system/main2-8bad9260.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/system/main2-4b538eea.js @@ -4,7 +4,7 @@ System.register([], function (exports, module) { execute: function () { exports('b', log); - var dep = exports('a', { x: 42 }) + var dep = exports('a', { x: 42 }); function log (x) { if (dep) { diff --git a/test/chunking-form/samples/entrypoint-facade/_expected/system/main2.js b/test/chunking-form/samples/entrypoint-facade/_expected/system/main2.js index 8744d8aaeb6..163d04b8852 100644 --- a/test/chunking-form/samples/entrypoint-facade/_expected/system/main2.js +++ b/test/chunking-form/samples/entrypoint-facade/_expected/system/main2.js @@ -1,4 +1,4 @@ -System.register(['./main2-8bad9260.js'], function (exports, module) { +System.register(['./main2-4b538eea.js'], function (exports, module) { 'use strict'; return { setters: [function (module) { diff --git a/test/form/samples/asi/_config.js b/test/form/samples/asi-var/_config.js similarity index 100% rename from test/form/samples/asi/_config.js rename to test/form/samples/asi-var/_config.js diff --git a/test/form/samples/asi/_expected.js b/test/form/samples/asi-var/_expected.js similarity index 100% rename from test/form/samples/asi/_expected.js rename to test/form/samples/asi-var/_expected.js diff --git a/test/form/samples/asi/c.js b/test/form/samples/asi-var/c.js similarity index 100% rename from test/form/samples/asi/c.js rename to test/form/samples/asi-var/c.js diff --git a/test/form/samples/asi/main.js b/test/form/samples/asi-var/main.js similarity index 100% rename from test/form/samples/asi/main.js rename to test/form/samples/asi-var/main.js From 752447d6eeb53ccd975c911c5fd4b66cb52fcac8 Mon Sep 17 00:00:00 2001 From: Guy Bedford Date: Tue, 15 May 2018 12:28:51 +0200 Subject: [PATCH 14/14] rebase corrections --- src/ast/nodes/Program.ts | 4 +- src/finalisers/cjs.ts | 54 +++++++++++++------ test/form/samples/compact/_expected/system.js | 2 +- .../samples/system-semicolon/_expected.js | 2 +- 4 files changed, 40 insertions(+), 22 deletions(-) diff --git a/src/ast/nodes/Program.ts b/src/ast/nodes/Program.ts index 9aff6b27705..b05368cbc5a 100644 --- a/src/ast/nodes/Program.ts +++ b/src/ast/nodes/Program.ts @@ -1,10 +1,8 @@ import MagicString from 'magic-string'; import { NodeBase, StatementNode } from './shared/Node'; import * as NodeType from './NodeType'; -import { RenderOptions, renderStatementList, findFirstLineBreakOutsideComment } from '../../utils/renderHelpers'; +import { RenderOptions, renderStatementList } from '../../utils/renderHelpers'; import { ExecutionPathOptions } from '../ExecutionPathOptions'; -import VariableDeclaration from './VariableDeclaration'; -import ExpressionStatement from './ExpressionStatement'; export default class Program extends NodeBase { type: NodeType.tProgram; diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index b930aa70e2e..a318dfe743b 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -39,7 +39,16 @@ export default function cjs( importBlock = ''; dependencies.forEach( - ({ id, namedExportsMode, isChunk, name, reexports, imports, exportsNames, exportsDefault }) => { + ({ + id, + namedExportsMode, + isChunk, + name, + reexports, + imports, + exportsNames, + exportsDefault + }) => { if (!reexports && !imports) { importBlock += definingVariable ? ';' : ','; definingVariable = false; @@ -62,22 +71,33 @@ export default function cjs( if (importBlock.length) importBlock += ';'; } else { importBlock = dependencies - .map(({ id, isChunk, name, reexports, imports, exportsNames, exportsDefault }) => { - if (!reexports && !imports) return `require('${id}');`; - - if (!interop || isChunk || !exportsDefault || !namedExportsMode) - return `${varOrConst} ${name} = require('${id}');`; - - needsInterop = true; - - if (exportsNames) - return ( - `${varOrConst} ${name} = require('${id}');` + - `\n${varOrConst} ${name}__default = _interopDefault(${name});` - ); - - return `${varOrConst} ${name} = _interopDefault(require('${id}'));`; - }) + .map( + ({ + id, + namedExportsMode, + isChunk, + name, + reexports, + imports, + exportsNames, + exportsDefault + }) => { + if (!reexports && !imports) return `require('${id}');`; + + if (!interop || isChunk || !exportsDefault || !namedExportsMode) + return `${varOrConst} ${name} = require('${id}');`; + + needsInterop = true; + + if (exportsNames) + return ( + `${varOrConst} ${name} = require('${id}');` + + `\n${varOrConst} ${name}__default = _interopDefault(${name});` + ); + + return `${varOrConst} ${name} = _interopDefault(require('${id}'));`; + } + ) .join('\n'); } diff --git a/test/form/samples/compact/_expected/system.js b/test/form/samples/compact/_expected/system.js index f79ffc31a94..e421580bee1 100644 --- a/test/form/samples/compact/_expected/system.js +++ b/test/form/samples/compact/_expected/system.js @@ -1,4 +1,4 @@ -System.register(['external'],function(exports,module){'use strict';var x;return{setters:[function(module){x=module.default;}],execute:function(){exports('default',foo$$1);var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); +System.register('foo',['external'],function(exports,module){'use strict';var x;return{setters:[function(module){x=module.default;}],execute:function(){exports('default',foo$$1);var self = {get default(){return foo$$1}};if(typeof Symbol!=='undefined'&&Symbol.toStringTag)Object.defineProperty(self,Symbol.toStringTag,{value:'Module'});else Object.defineProperty(self,'toString',{value:function(){return'[object Module]';}});/*#__PURE__*/Object.freeze(self);console.log(self); function foo$$1 () { console.log( x ); } diff --git a/test/form/samples/system-semicolon/_expected.js b/test/form/samples/system-semicolon/_expected.js index 63dfe614647..c64001ae262 100644 --- a/test/form/samples/system-semicolon/_expected.js +++ b/test/form/samples/system-semicolon/_expected.js @@ -5,7 +5,7 @@ System.register([], function (exports, module) { var main = exports('default', typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}) + typeof window !== "undefined" ? window : {}); } };