Skip to content
This repository was archived by the owner on Jan 18, 2022. It is now read-only.

Commit ab13f3b

Browse files
authored
fix: call transformer from whitelisted custom blocks (#310)
1 parent a983704 commit ab13f3b

File tree

6 files changed

+130
-45
lines changed

6 files changed

+130
-45
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
"runtime/"
4747
],
4848
"dependencies": {
49-
"@vue/component-compiler": "^4.1.0",
49+
"@vue/component-compiler": "^4.2.0",
5050
"@vue/component-compiler-utils": "^3.0.0",
5151
"debug": "^4.1.1",
5252
"hash-sum": "^1.0.2",

src/index.ts

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import {
44
parseVuePartRequest,
55
resolveVuePart,
66
isVuePartRequest,
7-
transformRequireToImport
7+
transformRequireToImport,
8+
DEFAULT_LANGS
89
} from './utils'
910
import {
1011
createDefaultCompiler,
@@ -183,11 +184,15 @@ export default function vue(opts: Partial<VuePluginOptions> = {}): Plugin {
183184
if (!opts.styleInjectorShadow)
184185
opts.styleInjectorShadow = '~' + require.resolve('../runtime/shadow')
185186

186-
createVuePartRequest.defaultLang = {
187-
...createVuePartRequest.defaultLang,
187+
const defaultLang: Record<string, string> = {
188+
...DEFAULT_LANGS,
188189
...opts.defaultLang
189190
}
190191

192+
if (opts.defaultLang && typeof opts.defaultLang.styles === 'string') {
193+
defaultLang.style = opts.defaultLang.styles
194+
}
195+
191196
const shouldExtractCss = opts.css === false
192197
const customBlocks: string[] = []
193198

@@ -269,10 +274,10 @@ export default function vue(opts: Partial<VuePluginOptions> = {}): Plugin {
269274

270275
resolveId(id, importer) {
271276
const request = id
272-
273-
if (!importer) return
277+
278+
if (!importer) return
274279
if (!isVuePartRequest(id)) return
275-
280+
276281
id = path.resolve(path.dirname(importer), id)
277282
const ref = parseVuePartRequest(id)
278283

@@ -307,7 +312,12 @@ export default function vue(opts: Partial<VuePluginOptions> = {}): Plugin {
307312
let map = element.map as any
308313

309314
if (request.meta.type === 'styles') {
310-
code = prependStyle(id, request.meta.lang, code, map).code
315+
code = prependStyle(
316+
id,
317+
request.meta.lang || defaultLang.style,
318+
code,
319+
map
320+
).code
311321
}
312322

313323
dL(`id: ${id}\ncode: \n${code}\nmap: ${JSON.stringify(map, null, 2)}\n\n`)
@@ -344,7 +354,7 @@ export default function vue(opts: Partial<VuePluginOptions> = {}): Plugin {
344354
if (style.content) {
345355
style.content = prependStyle(
346356
filename,
347-
style.lang || 'css',
357+
style.lang || defaultLang.style,
348358
style.content,
349359
style.map
350360
).code
@@ -388,12 +398,12 @@ export default function vue(opts: Partial<VuePluginOptions> = {}): Plugin {
388398
code: `
389399
export * from '${createVuePartRequest(
390400
filename,
391-
descriptor.script.lang || 'js',
401+
descriptor.script.lang || defaultLang.script,
392402
'script'
393403
)}'
394404
import script from '${createVuePartRequest(
395405
filename,
396-
descriptor.script.lang || 'js',
406+
descriptor.script.lang || defaultLang.script,
397407
'script'
398408
)}'
399409
export default script
@@ -433,22 +443,23 @@ export default function vue(opts: Partial<VuePluginOptions> = {}): Plugin {
433443
.filter(Boolean)
434444
}
435445

446+
// Why?
436447
input.script.code = input.script.code.replace(/^\s+/gm, '')
437448

438449
const result = assemble(compiler, filename, beforeAssemble(input), opts)
439450

440451
descriptor.customBlocks.forEach((block, index) => {
441452
if (!isAllowed(block.type)) return
453+
const lang =
454+
typeof block.attrs.lang === 'string'
455+
? block.attrs.lang
456+
: defaultLang[block.type] || block.type
457+
const id = createVuePartRequest(filename, lang, block.type, index)
442458
result.code +=
443459
'\n' +
444-
`export * from '${createVuePartRequest(
445-
filename,
446-
(typeof block.attrs.lang === 'string' && block.attrs.lang) ||
447-
createVuePartRequest.defaultLang[block.type] ||
448-
block.type,
449-
'customBlocks',
450-
index
451-
)}'`
460+
`export * from '${id}'\n` +
461+
`import __custom_block_${index}__ from '${id}'\n` +
462+
`__custom_block_${index}__(__vue_component__)`
452463
})
453464

454465
dT(

src/utils.ts

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,6 @@ export interface VuePartRequestMeta {
2121
index?: number
2222
}
2323

24-
export interface VuePartRequestCreator {
25-
(filename: string, lang: string, type: string, index?: number): string
26-
27-
defaultLang: {
28-
[key: string]: string
29-
}
30-
}
31-
3224
export function createVueFilter(
3325
include: Array<string | RegExp> | string | RegExp = [/\.vue$/i],
3426
exclude: Array<string | RegExp> | string | RegExp = []
@@ -49,7 +41,11 @@ export function getVueMetaFromQuery(id: string): VuePartRequestMeta | null {
4941
? (query[PARAM_NAME] as any)[0]
5042
: query[PARAM_NAME]) as string
5143

52-
const [type, index, lang] = data.split('.')
44+
let [type, index, lang] = data.split('.')
45+
46+
if (!/^(template|styles|script)$/i.test(type)) {
47+
type = 'customBlocks'
48+
}
5349

5450
return (lang
5551
? { type, lang, index: parseInt(index) } // styles.0.css
@@ -64,13 +60,13 @@ export function isVuePartRequest(id: string): boolean {
6460
return getVueMetaFromQuery(id) !== null
6561
}
6662

67-
export const createVuePartRequest: VuePartRequestCreator = ((
63+
export function createVuePartRequest(
6864
filename: string,
6965
lang: string | undefined,
7066
type: string,
7167
index?: number
72-
): string => {
73-
lang = lang || createVuePartRequest.defaultLang[type]
68+
): string {
69+
lang = DEFAULT_LANGS[type] || lang
7470

7571
const match = GET_QUERY.exec(filename)
7672

@@ -81,12 +77,14 @@ export const createVuePartRequest: VuePartRequestCreator = ((
8177
.join('.')
8278

8379
return `${path.basename(filename)}?${queryString.stringify(query)}`
84-
}) as VuePartRequestCreator
80+
}
8581

86-
createVuePartRequest.defaultLang = {
82+
export const DEFAULT_LANGS: Record<string, string> = {
8783
template: 'html',
88-
styles: 'css',
89-
script: 'js'
84+
style: 'css',
85+
script: 'js',
86+
docs: 'md',
87+
i18n: 'json'
9088
}
9189

9290
export function parseVuePartRequest(id: string): VuePartRequest | undefined {
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Jest Snapshot v1, https://goo.gl/fbAQLP
2+
3+
exports[`customBlocks transform 1`] = `
4+
"var __custom_block_1__ = \\"// My Docs Block\\";
5+
6+
/* script */
7+
8+
/* template */
9+
var __vue_render__ = function() {
10+
var _vm = this;
11+
var _h = _vm.$createElement;
12+
var _c = _vm._self._c || _h;
13+
return _c(\\"div\\", [_vm._v(\\"Hello, world\\")])
14+
};
15+
var __vue_staticRenderFns__ = [];
16+
__vue_render__._withStripped = true;
17+
18+
/* style */
19+
const __vue_inject_styles__ = undefined;
20+
/* scoped */
21+
const __vue_scope_id__ = undefined;
22+
/* module identifier */
23+
const __vue_module_identifier__ = undefined;
24+
/* functional template */
25+
const __vue_is_functional_template__ = false;
26+
/* component normalizer */
27+
const __vue_normalize__ = vue-runtime-helpers/dist/normalize-component.mjs;
28+
/* style inject */
29+
30+
/* style inject SSR */
31+
32+
/* style inject shadow dom */
33+
34+
35+
36+
const __vue_component__ = __vue_normalize__(
37+
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
38+
__vue_inject_styles__,
39+
{},
40+
__vue_scope_id__,
41+
__vue_is_functional_template__,
42+
__vue_module_identifier__,
43+
false,
44+
undefined,
45+
undefined,
46+
undefined
47+
);
48+
__custom_block_1__(__vue_component__);
49+
50+
export default __vue_component__;
51+
"
52+
`;

test/options/custom-blocks.spec.ts

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
11
import vue, { VuePluginOptions } from '../../src'
22
import { pluginInline } from '../setup/plugins'
33
import { rollup } from 'rollup'
4+
function pluginText() {
5+
return {
6+
name: 'text',
7+
transform(source: string, id: string) {
8+
if (/\.(md|txt)$/.test(id)) {
9+
return `export default ${JSON.stringify(source.trim())}`
10+
}
11+
},
12+
}
13+
}
414

515
describe('customBlocks', () => {
616
async function setup(options?: Partial<VuePluginOptions>) {
@@ -21,11 +31,16 @@ describe('customBlocks', () => {
2131
</docs>
2232
`
2333
),
34+
pluginText(),
2435
vue({
2536
...options,
26-
normalizer: 'vue-runtime-helpers/dist/normalize-component.mjs'
27-
})
28-
]
37+
defaultLang: {
38+
docs: 'md',
39+
custom: 'txt',
40+
},
41+
normalizer: 'vue-runtime-helpers/dist/normalize-component.mjs',
42+
}),
43+
],
2944
})
3045
.then(bundle => bundle.generate({ format: 'es' }))
3146
.then(generated => generated.output[0])
@@ -40,15 +55,15 @@ describe('customBlocks', () => {
4055

4156
it('array of tags', async () => {
4257
const { code } = await setup({
43-
customBlocks: ['custom']
58+
customBlocks: ['custom'],
4459
})
4560

4661
expect(code).toEqual(expect.stringContaining('My Custom Block'))
4762
expect(code).not.toEqual(expect.stringContaining('My Docs Block'))
4863
})
4964
it('negative array of tags', async () => {
5065
const { code } = await setup({
51-
customBlocks: ['*', '!custom']
66+
customBlocks: ['*', '!custom'],
5267
})
5368

5469
expect(code).not.toEqual(expect.stringContaining('My Custom Block'))
@@ -58,10 +73,19 @@ describe('customBlocks', () => {
5873
const { code } = await setup({
5974
customBlocks(tag) {
6075
return tag === 'custom'
61-
}
76+
},
6277
})
6378

6479
expect(code).toEqual(expect.stringContaining('My Custom Block'))
6580
expect(code).not.toEqual(expect.stringContaining('My Docs Block'))
6681
})
82+
83+
it('transform', async () => {
84+
const { code } = await setup({
85+
customBlocks: ['docs'],
86+
})
87+
88+
expect(code).toEqual(expect.stringContaining('__custom_block_1__(__vue_component__)'))
89+
expect(code).toMatchSnapshot()
90+
})
6791
})

yarn.lock

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1571,10 +1571,10 @@
15711571
source-map "~0.6.1"
15721572
vue-template-es2015-compiler "^1.9.0"
15731573

1574-
"@vue/component-compiler@^4.1.0":
1575-
version "4.1.0"
1576-
resolved "https://registry.yarnpkg.com/@vue/component-compiler/-/component-compiler-4.1.0.tgz#92ccb90e425aa7e61d58bf092a5cfcdd6d0f9315"
1577-
integrity sha512-20S7mm7CYP94m2Morw2ftz1tqoBu1nX7KYiqo5rlgKPZ0dlY7VZX7wAL/etN3s4HD0PBeenr1pUUCBIgGSaB2g==
1574+
"@vue/component-compiler@^4.2.0":
1575+
version "4.2.0"
1576+
resolved "https://registry.yarnpkg.com/@vue/component-compiler/-/component-compiler-4.2.0.tgz#437855cd59f3d713a4eef81bac7ab0f4950977b4"
1577+
integrity sha512-bxFNxUpKzLfHDoGTsAe2w7gEz4OwII7tp5m7sAXES1DApbpYglH4YSpYxdZRZ4GN/wj2fPD0u72QRJXd4UPvFQ==
15781578
dependencies:
15791579
"@vue/component-compiler-utils" "^3.0.0"
15801580
clean-css "^4.1.11"

0 commit comments

Comments
 (0)