Skip to content

Commit

Permalink
feat(core): Add inline source-maps
Browse files Browse the repository at this point in the history
This provides error information in the browser. Including the original source

Fixes: #198
  • Loading branch information
tucker87 authored and Jason Tucker committed Oct 13, 2024
1 parent bed17ac commit 8ee6bf1
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 18 deletions.
2 changes: 1 addition & 1 deletion build/rollup.config-node.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const __dirname = fileURLToPath(new URL('.', import.meta.url))
import pkg from '../package.json' assert { type: 'json' };


const genSourcemap = false;
const genSourcemap = "inline";

async function configFactory({ name, vueTarget, libraryTargetModule }) {

Expand Down
2 changes: 1 addition & 1 deletion build/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const configure = ({name, vueTarget, libraryTargetModule}) => async (env = {}, {
}
}));

const genSourcemap = false;
const genSourcemap = "inline";

let actualTargetsBrowsers = targetsBrowsers;

Expand Down
4 changes: 2 additions & 2 deletions src/createVue2SFCModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import { version, vueVersion } from './index'
// @ts-ignore
const targetBrowserBabelPluginsHash : string = hash(...Object.keys({ ...(typeof ___targetBrowserBabelPlugins !== 'undefined' ? ___targetBrowserBabelPlugins : {}) }));

const genSourcemap : boolean = !!process.env.GEN_SOURCEMAP;
const genSourcemap : boolean | "inline" = process.env.GEN_SOURCEMAP;

/**
* @internal
Expand Down Expand Up @@ -88,7 +88,7 @@ export async function createSFCModule(source : string, filename : AbstractPath,
const descriptor = sfc_parse({
source,
filename: strFilename,
needMap: genSourcemap,
needMap: !!genSourcemap,
compiler: vueTemplateCompiler as VueTemplateCompiler}
);

Expand Down
25 changes: 18 additions & 7 deletions src/createVue3SFCModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,22 @@ type PreprocessLang = SFCAsyncStyleCompileOptions['preprocessLang'];
* the version of the library
*/
import { version, vueVersion } from './index'
import { RawSourceMap } from '@vue/component-compiler-utils/dist/types'

// @ts-ignore
const targetBrowserBabelPluginsHash : string = hash(...Object.keys({ ...(typeof ___targetBrowserBabelPlugins !== 'undefined' ? ___targetBrowserBabelPlugins : {}) }));

const genSourcemap : boolean = !!process.env.GEN_SOURCEMAP;
const genSourcemap : boolean | "inline" = process.env.GEN_SOURCEMAP;

/**
* @internal
*/
const isProd : boolean = process.env.NODE_ENV === 'production';


/**
* @internal
*/
const buildMapComment = (map : RawSourceMap) => `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(JSON.stringify(map))}`

/**
* @internal
Expand Down Expand Up @@ -87,7 +91,7 @@ export async function createSFCModule(source : string, filename : AbstractPath,
// vue-loader next: https://github.com/vuejs/vue-loader/blob/next/src/index.ts#L91
const { descriptor, errors } = sfc_parse(source, {
filename: strFilename,
sourceMap: genSourcemap,
sourceMap: !!genSourcemap,
});


Expand All @@ -111,13 +115,14 @@ export async function createSFCModule(source : string, filename : AbstractPath,

const compileTemplateOptions : SFCTemplateCompileOptions|undefined = descriptor.template ? {
// hack, since sourceMap is not configurable an we want to get rid of source-map dependency. see genSourcemap
compiler: { ...vue_CompilerDOM, compile: (template, opts) => vue_CompilerDOM.compile(template, { ...opts, sourceMap: genSourcemap }) },
compiler: { ...vue_CompilerDOM, compile: (template, options) => vue_CompilerDOM.compile(template, { ...options, sourceMap: !!genSourcemap }) },
source: descriptor.template.src ? (await (await getResource({ refPath: filename, relPath: descriptor.template.src }, options).getContent()).getContentData(false)) as string : descriptor.template.content,
filename: descriptor.filename,
isProd,
scoped: hasScoped,
id: scopeId,
slotted: descriptor.slotted,
inMap: descriptor.template.map,
compilerOptions: {
isCustomElement,
whitespace,
Expand Down Expand Up @@ -170,7 +175,7 @@ export async function createSFCModule(source : string, filename : AbstractPath,
// src: https://github.com/vuejs/vue-next/blob/15baaf14f025f6b1d46174c9713a2ec517741d0d/packages/compiler-sfc/src/compileScript.ts#L43
const scriptBlock = sfc_compileScript(descriptor, {
isProd,
sourceMap: genSourcemap,
sourceMap: !!genSourcemap,
id: scopeId,
// @ts-ignore (unstable resolution: node_modules/@babel/parser/typings/babel-parser vs node_modules/@types/babel__core/node_modules/@babel/parser/typings/babel-parser)
babelParserPlugins: [ ...contextBabelParserPlugins, ...additionalBabelParserPlugins ], // [...babelParserDefaultPlugins, 'jsx'] + additionalBabelParserPlugins // babelParserDefaultPlugins = [ 'bigInt', 'optionalChaining', 'nullishCoalescingOperator' ]
Expand All @@ -180,6 +185,9 @@ export async function createSFCModule(source : string, filename : AbstractPath,
templateOptions: compileTemplateOptions,
});

if(scriptBlock.map)
scriptBlock.content += `\r\n${buildMapComment(scriptBlock.map)}`

// note:
// scriptBlock.content is the script code after vue transformations
// scriptBlock.scriptAst is the script AST before vue transformations
Expand All @@ -192,7 +200,7 @@ export async function createSFCModule(source : string, filename : AbstractPath,
compileTemplateOptions.compilerOptions.bindingMetadata = bindingMetadata;

await loadDeps(filename, depsList, options);
Object.assign(component, interopRequireDefault(createCJSModule(filename, transformedScriptSource, options).exports).default);
Object.assign(component, interopRequireDefault((await createCJSModule(filename, transformedScriptSource, options)).exports).default);
}


Expand Down Expand Up @@ -237,11 +245,14 @@ export async function createSFCModule(source : string, filename : AbstractPath,
for ( const err of template.tips )
log?.('info', 'SFC template', err);

if(template.map)
template.code += `\r\n${buildMapComment(template.map)}`

return await transformJSCode(template.code, true, descriptor.filename, additionalBabelParserPlugins, additionalBabelPlugins, log, devMode);
});

await loadDeps(filename, templateDepsList, options);
Object.assign(component, createCJSModule(filename, templateTransformedSource, options).exports);
Object.assign(component, (await createCJSModule(filename, templateTransformedSource, options)).exports);
}


Expand Down
35 changes: 29 additions & 6 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import { createSFCModule } from './createSFCModule'
/**
* @internal
*/
const genSourcemap : boolean = !!process.env.GEN_SOURCEMAP;
const genSourcemap : boolean | "inline" = process.env.GEN_SOURCEMAP;

const version : string = process.env.VERSION as string;

Expand Down Expand Up @@ -253,7 +253,7 @@ export async function transformJSCode(source : string, moduleSourceType : boolea
comments: devMode,
retainLines: devMode,
//envName: devMode ? 'development' : 'production', see 'process.env.BABEL_ENV': JSON.stringify(mode),

filename: filename.toString(),
//minified,
sourceType: moduleSourceType ? 'module' : 'script',
});
Expand Down Expand Up @@ -324,7 +324,7 @@ export async function loadModuleInternal(pathCx : PathContext, options : Options
* Create a cjs module
* @internal
*/
export function defaultCreateCJSModule(refPath : AbstractPath, source : string, options : Options) : Module {
export async function defaultCreateCJSModule(refPath : AbstractPath, source : string, options : Options) : Promise<Module> {

const { moduleCache, pathResolve, getResource } = options;

Expand All @@ -348,8 +348,31 @@ export function defaultCreateCJSModule(refPath : AbstractPath, source : string,

// see https://github.com/nodejs/node/blob/a46b21f556a83e43965897088778ddc7d46019ae/lib/internal/modules/cjs/loader.js#L195-L198
// see https://github.com/nodejs/node/blob/a46b21f556a83e43965897088778ddc7d46019ae/lib/internal/modules/cjs/loader.js#L1102
const moduleFunction = Function('exports', 'require', 'module', '__filename', '__dirname', '__vsfcl_import__', source);
moduleFunction.call(module.exports, module.exports, require, module, refPath, pathResolve({ refPath, relPath: '.' }, options), importFunction);
const wrappedSource = `(exports, require, module, __filename, __dirname, __vsfcl_import__) => { ${source} \r\n }`

let ast = babel_parse(wrappedSource, {
sourceType: 'module',
sourceFilename: refPath.toString(),
});

const transformedScript = await babel_transformFromAstAsync(ast, wrappedSource, {
sourceMaps: "inline",
babelrc: false,
configFile: false,
highlightCode: false,
filename: refPath.toString(),
sourceType: 'module',
});

if ( transformedScript === null || transformedScript.code == null ) { // == null or undefined

const msg = `unable to transform script "${refPath.toString()}"`;
options.log?.('error', msg);
throw new Error(msg)
}


eval(transformedScript.code)(module.exports, require, module, refPath, pathResolve({ refPath, relPath: '.' }, options), importFunction)

return module;
}
Expand Down Expand Up @@ -379,7 +402,7 @@ export async function createJSModule(source : string, moduleSourceType : boolean
});

await loadDeps(filename, depsList, options);
return createCJSModule(filename, transformedSource, options).exports;
return (await createCJSModule(filename, transformedSource, options)).exports;
}


Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ export type Options = {
* creates a CommonJS module from JS source string.
* *(optional)*
*/
createCJSModule(refPath : AbstractPath, source : string, options : Options) : Module,
createCJSModule(refPath : AbstractPath, source : string, options : Options) : Promise<Module>,



Expand Down

0 comments on commit 8ee6bf1

Please sign in to comment.