From 06231a7bc925a8fb928ed2f2162d97530035f8be Mon Sep 17 00:00:00 2001 From: Cologler Date: Mon, 13 Sep 2021 22:55:21 +0800 Subject: [PATCH] feat: preserve indentation --- src/index.js | 13 ++++++++++--- test/fixtures/css/style.css | 32 ++++++++++++++++---------------- test/fixtures/template/head.html | 4 ++-- 3 files changed, 28 insertions(+), 21 deletions(-) diff --git a/src/index.js b/src/index.js index 480e2db..182157a 100644 --- a/src/index.js +++ b/src/index.js @@ -17,13 +17,20 @@ const inject = () => { return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported')) } - const regex = /(?:|\*\/)/gi + const regex = /[\t ]*(?:|\*\/)/gi - const newFileContents = String(file.contents).replace(regex, (_, src) => { + const newFileContents = String(file.contents).replace(regex, (g0, src) => { + const prefix = g0.match(/^[\t ]*/)[0] || '' const sourcePath = src.startsWith('/') ? path.join(process.cwd(), src) : path.join(file.dirname, src) - return String(fs.readFileSync(sourcePath)) + const content = String(fs.readFileSync(sourcePath)) + return content + .split('\n') + .map(line => + line && line.trim() ? prefix + line : line.endsWith('\r') ? '\r' : '' + ) + .join('\n') }) file.contents = Buffer.from(newFileContents) diff --git a/test/fixtures/css/style.css b/test/fixtures/css/style.css index 0fbbcd6..9cc7a64 100644 --- a/test/fixtures/css/style.css +++ b/test/fixtures/css/style.css @@ -1,21 +1,21 @@ body { - width: 100vw; - height: 100vh; + width: 100vw; + height: 100vh; - margin: 0; - padding: 0; + margin: 0; + padding: 0; - display: flex; - align-items: center; - justify-content: center; - align-content: center; + display: flex; + align-items: center; + justify-content: center; + align-content: center; - background-color: #4a596b; - } - h1 { - width: 50%; - color: #eeeeee; + background-color: #4a596b; +} +h1 { + width: 50%; + color: #eeeeee; - text-align: center; - font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; - } \ No newline at end of file + text-align: center; + font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; +} \ No newline at end of file diff --git a/test/fixtures/template/head.html b/test/fixtures/template/head.html index 060feae..7ef1906 100644 --- a/test/fixtures/template/head.html +++ b/test/fixtures/template/head.html @@ -1,3 +1,3 @@ - - \ No newline at end of file + + \ No newline at end of file