From 075cda18bc537298c5225072ba0c99d7b4d41ff3 Mon Sep 17 00:00:00 2001 From: Nathan Burkiewicz Date: Wed, 7 Oct 2020 21:26:52 +0200 Subject: [PATCH] Recovers webpack magic comments and adds to import 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. --- snowpack/src/rewrite-imports.ts | 9 ++++++++- test/build/__snapshots__/build.test.js.snap | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/snowpack/src/rewrite-imports.ts b/snowpack/src/rewrite-imports.ts index e95d5a9fa8..646bad2203 100644 --- a/snowpack/src/rewrite-imports.ts +++ b/snowpack/src/rewrite-imports.ts @@ -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); } @@ -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); } diff --git a/test/build/__snapshots__/build.test.js.snap b/test/build/__snapshots__/build.test.js.snap index 4cb85ef51d..ad5182507c 100644 --- a/test/build/__snapshots__/build.test.js.snap +++ b/test/build/__snapshots__/build.test.js.snap @@ -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`] = `