Skip to content

Commit

Permalink
Recovers webpack magic comments and adds to import (#1243)
Browse files Browse the repository at this point in the history
Webpack's magic comments must be extracted from dynamic imports before the spec is passed to `matchDynamicImportValue`. If a match is found for these types of comments, they are appended to the rewritten import.
  • Loading branch information
N8-B authored Oct 8, 2020
1 parent f269fa6 commit 55fb2f7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
9 changes: 8 additions & 1 deletion snowpack/src/rewrite-imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {matchDynamicImportValue} from './scan-imports';

const {parse} = require('es-module-lexer');

const WEBPACK_MAGIC_COMMENT_REGEX = /\/\*[\s\S]*?\*\//g;

function spliceString(source: string, withSlice: string, start: number, end: number) {
return source.slice(0, start) + (withSlice || '') + source.slice(end);
}
Expand Down Expand Up @@ -32,12 +34,17 @@ export async function transformEsmImports(
let rewrittenCode = _code;
for (const imp of imports.reverse()) {
let spec = rewrittenCode.substring(imp.s, imp.e);
let webpackMagicCommentMatches;
if (imp.d > -1) {
// Extracting comments from spec as they are stripped in `matchDynamicImportValue`
webpackMagicCommentMatches = spec.match(WEBPACK_MAGIC_COMMENT_REGEX);
spec = matchDynamicImportValue(spec) || '';
}
let rewrittenImport = replaceImport(spec);
if (imp.d > -1) {
rewrittenImport = JSON.stringify(rewrittenImport);
rewrittenImport = webpackMagicCommentMatches
? `${webpackMagicCommentMatches.join(' ')} ${JSON.stringify(rewrittenImport)}`
: JSON.stringify(rewrittenImport);
}
rewrittenCode = spliceString(rewrittenCode, rewrittenImport, imp.s, imp.e);
}
Expand Down
2 changes: 1 addition & 1 deletion test/build/__snapshots__/build.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ import def, {
all/* , */,
} from '../web_modules/async.js';
console.log(def, waterfall, all);
import(\\"../web_modules/array-flatten.js\\")"
import(/* webpackChunkName: \\"array-flatten\\" */ \\"../web_modules/array-flatten.js\\")"
`;

exports[`snowpack build config-treeshake: allFiles 1`] = `
Expand Down

1 comment on commit 55fb2f7

@vercel
Copy link

@vercel vercel bot commented on 55fb2f7 Oct 8, 2020

Choose a reason for hiding this comment

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

Please sign in to comment.