Skip to content

Commit

Permalink
feat: support sourcemap
Browse files Browse the repository at this point in the history
  • Loading branch information
anncwb committed Feb 6, 2021
1 parent aa04d52 commit 8c3cd9d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vite-plugin-mock",
"version": "2.0.1",
"version": "2.1.0",
"description": "A mock plugin for vite",
"main": "dist/index.js",
"files": [
Expand Down
28 changes: 23 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ export function viteMockServe(opt: ViteMockOptions): Plugin {
let isDev = false;

let config: ResolvedConfig;

let needSourcemap = false;
return {
name: 'vite:mock',
enforce: 'pre',
configResolved(resolvedConfig) {
config = resolvedConfig;
isDev = config.command === 'serve' && !config.isProduction;
needSourcemap = resolvedConfig.isProduction && !!resolvedConfig.build.sourcemap;
},

configureServer: ({ middlewares }) => {
const { localEnabled = isDev } = opt;
if (!localEnabled) return;
Expand All @@ -30,16 +34,30 @@ export function viteMockServe(opt: ViteMockOptions): Plugin {
middlewares.use(bodyParser.json());
middlewares.use(requestMiddle(opt));
},

async transform(code: string, id: string) {
if (isDev || !id.endsWith(injectFile)) return code;
const getMap = () => (needSourcemap ? this.getCombinedSourcemap() : null);

if (isDev || !id.endsWith(injectFile)) {
return {
code,
map: getMap(),
};
}
const { prodEnabled = true, injectCode = '' } = opt;
if (!prodEnabled) return;
return `
if (!prodEnabled) {
return {
code,
map: getMap(),
};
}
return {
code: `
${code}
\n
${injectCode}
`;
`,
map: getMap(),
};
},
};
}
Expand Down

0 comments on commit 8c3cd9d

Please sign in to comment.