Skip to content

Commit

Permalink
fix(build): resolve template assets reference on build
Browse files Browse the repository at this point in the history
fix #15
  • Loading branch information
underfin committed Jan 8, 2021
1 parent 4a2f092 commit cf06627
Showing 1 changed file with 33 additions and 5 deletions.
38 changes: 33 additions & 5 deletions template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,19 @@ export function compileSFCTemplate(
source: string,
block: SFCBlock,
filename: string,
{ root, isProduction, vueTemplateOptions }: ResolvedOptions,
{ root, isProduction, vueTemplateOptions, devServer }: ResolvedOptions,
pluginContext: TransformPluginContext
): string {
const { tips, errors, code } = compileTemplate({
source,
filename,
compiler: vueTemplateCompiler as any,
transformAssetUrls: true,
transformAssetUrlsOptions: {
base: path.posix.dirname(path.relative(root, filename)),
},
transformAssetUrlsOptions: devServer
? {
base: path.posix.dirname(path.relative(root, filename)),
}
: {},
isProduction,
isFunctional: !!block.attrs.functional,
optimizeSSR: false,
Expand All @@ -35,5 +37,31 @@ export function compileSFCTemplate(
// errors.forEach((e) => pluginContext.error(e))
}

return code + `\nexport { render, staticRenderFns }`
if (devServer) {
return code + `\nexport { render, staticRenderFns }`
}
// rewrite require calls to import on build
return transformRequireToImport(code) + `\nexport { render, staticRenderFns }`
}

export function transformRequireToImport(code: string): string {
const imports: { [key: string]: string } = {}
let strImports = ''

code = code.replace(
/require\(("(?:[^"\\]|\\.)+"|'(?:[^'\\]|\\.)+')\)/g,
(_, name): any => {
if (!(name in imports)) {
imports[name] = `__$_require_${name
.replace(/[^a-z0-9]/g, '_')
.replace(/_{2,}/g, '_')
.replace(/^_|_$/g, '')}__`
strImports += 'import ' + imports[name] + ' from ' + name + '\n'
}

return imports[name]
}
)

return strImports + code
}

0 comments on commit cf06627

Please sign in to comment.