mirror of
https://github.com/storybookjs/storybook.git
synced 2025-04-04 19:11:08 +08:00
reparsing to insert the slice of code in the right place
This commit is contained in:
parent
cb1fe948e3
commit
9bac963210
@ -28,7 +28,7 @@ export function webpack(webpackConfig: any = {}, options: any = {}) {
|
||||
{
|
||||
test: /\.(stories|story)\.[tj]sx?$/,
|
||||
loader: require.resolve('@storybook/source-loader'),
|
||||
options: sourceLoaderOptions,
|
||||
options: { ...sourceLoaderOptions, inspectLocalDependencies: true },
|
||||
enforce: 'pre',
|
||||
},
|
||||
]
|
||||
|
@ -149,6 +149,22 @@ export function findDependencies(ast) {
|
||||
return { dependencies, storiesOfIdentifiers };
|
||||
}
|
||||
|
||||
export function endOfImports(ast) {
|
||||
let end = 0;
|
||||
|
||||
estraverse.traverse(ast, {
|
||||
fallback: 'iteration',
|
||||
enter: node => {
|
||||
patchNode(node);
|
||||
|
||||
if (node.type === 'ImportDeclaration') {
|
||||
end = Math.max(node.end, end);
|
||||
}
|
||||
},
|
||||
});
|
||||
return end;
|
||||
}
|
||||
|
||||
export function popParametersObjectFromDefaultExport(source, ast) {
|
||||
let splicedSource = source;
|
||||
let parametersSliceOfCode = '';
|
||||
|
@ -1,19 +1,24 @@
|
||||
import getOptions from 'loader-utils';
|
||||
import { readStory } from './dependencies-lookup/readAsObject';
|
||||
import { getRidOfUselessFilePrefixes } from './dependencies-lookup/getRidOfUselessFilePrefixes';
|
||||
import getParser from './abstract-syntax-tree/parsers';
|
||||
import { endOfImports } from './abstract-syntax-tree/traverse-helpers';
|
||||
|
||||
export function insertAfterImports(insert, source) {
|
||||
let start = source.lastIndexOf('\nimport ');
|
||||
if (start === -1) {
|
||||
start = 0;
|
||||
} else {
|
||||
if (/import\s+{/.test(source.slice(start + 1, start + 10))) {
|
||||
start = source.indexOf('}', start + 1);
|
||||
}
|
||||
start = 1 + source.indexOf('\n', start + 1);
|
||||
export function insertAfterImports(classLoader, insert, source) {
|
||||
const options = getOptions(classLoader) || {};
|
||||
let ast;
|
||||
try {
|
||||
ast = getParser(options.parser || classLoader.extension || 'javascript').parse(source);
|
||||
} catch (e) {
|
||||
// if not working, then we will fallback to not adding anything
|
||||
// perhaps the code was not written in javascript
|
||||
return source;
|
||||
}
|
||||
const imports = source.slice(0, start);
|
||||
const rest = source.slice(start);
|
||||
return `${imports}${insert}${rest}`;
|
||||
if (!ast) return `${insert}${source}`;
|
||||
const endOfImportsIndex = endOfImports(ast);
|
||||
return `${source.substring(0, endOfImportsIndex)}\n${insert}\n${source.substring(
|
||||
endOfImports + 1
|
||||
)}`;
|
||||
}
|
||||
|
||||
export function transform(inputSource) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user