Best JavaScript code snippet using storybook-root
dts-localize.ts
Source:dts-localize.ts
1/* eslint-disable no-param-reassign */2import path from 'path';3import fs from 'fs-extra';4import { sync } from 'read-pkg-up';5import * as ts from 'typescript';6const parseConfigHost = {7 useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,8 readDirectory: ts.sys.readDirectory,9 fileExists: ts.sys.fileExists,10 readFile: ts.sys.readFile,11};12function getAbsolutePath(fileName: string, cwd?: string) {13 if (!path.isAbsolute(fileName)) {14 fileName = path.join(cwd !== undefined ? cwd : process.cwd(), fileName);15 }16 return fileName;17}18function getCompilerOptions(inputFileNames: string[], preferredConfigPath?: string) {19 const configFileName =20 preferredConfigPath !== undefined ? preferredConfigPath : findConfig(inputFileNames);21 const configParseResult = ts.readConfigFile(configFileName, ts.sys.readFile);22 const compilerOptionsParseResult = ts.parseJsonConfigFileContent(23 configParseResult.config,24 parseConfigHost,25 path.resolve(path.dirname(configFileName)),26 undefined,27 getAbsolutePath(configFileName)28 );29 return compilerOptionsParseResult.options;30}31function findConfig(inputFiles: string[]) {32 if (inputFiles.length !== 1) {33 throw new Error(34 'Cannot find tsconfig for multiple files. Please specify preferred tsconfig file'35 );36 }37 // input file could be a relative path to the current path38 // and desired config could be outside of current cwd folder39 // so we have to provide absolute path to find config until the root40 const searchPath = getAbsolutePath(inputFiles[0]);41 const configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists);42 if (!configFileName) {43 throw new Error(`Cannot find config file for file ${searchPath}`);44 }45 return configFileName;46}47interface Options {48 externals: string[];49 cwd?: string;50}51export const run = async (entrySourceFiles: string[], outputPath: string, options: Options) => {52 const compilerOptions = getCompilerOptions(entrySourceFiles);53 const host = ts.createCompilerHost(compilerOptions);54 const cwd = options.cwd || process.cwd();55 const pkg = sync({ cwd }).packageJson;56 const externals = Object.keys({ ...pkg.dependencies, ...pkg.peerDependencies });57 // this to make paths for local packages as they are in node_modules because of yarn58 // but it depends on the way you handle "flatting of files"59 // so basically you can remove this host completely if you handle it in different way60 host.realpath = (p: string) => p;61 const program = ts.createProgram(entrySourceFiles, compilerOptions, host);62 const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed, removeComments: false });63 const typeChecker = program.getTypeChecker();64 const sourceFiles = program.getSourceFiles();65 const filesRemapping = new Map<string, string>();66 const replaceRemapping = new Map<string, string[]>();67 entrySourceFiles.forEach((file) => {68 const sourceFile = sourceFiles.find((f) => f.fileName === file);69 actOnSourceFile(sourceFile);70 });71 /**72 * @param {string} basePath the path is the directory where the package.json is located73 * @param {string} filePath the path of the current file74 */75 function getReplacementPathRelativeToBase(basePath: string, filePath: string) {76 const relative = path.relative(basePath, filePath);77 let newPath = '';78 /*79 first we work out the relative path from the basePath80 we might get a path like: ../../node_modules/packagename/dist/dir/file.ts81 Here's a few examples of what the idea is:82 ../../node_modules/packagename/dist/dir/file.ts => _modules/packagename-dist-dir-file.ts83 ../../node_modules/packagename/node_modules/b/dist/dir/file.ts => _modules/packagename-node_modules-b-dist-dir-file.ts84 ./node_modules/packagename/dist/dir/file.ts => _modules/packagename-dist-dir-file.ts85 ./dist/ts-tmp/file.ts => file.ts86 87 */88 if (relative.includes('node_modules/')) {89 const [, ...parts] = relative.split('node_modules/');90 const filename = parts.join('node_modules/').split('/').join('-');91 newPath = path.join(outputPath, '_modules', filename);92 } else if (relative.includes('dist/ts-tmp/')) {93 const [, ...parts] = relative.split('dist/ts-tmp/');94 const filename = parts.join('').split('/').join('-');95 newPath = path.join(outputPath, filename);96 } else {97 const filename = relative.split('/').join('-');98 newPath = path.join(outputPath, filename);99 }100 return newPath;101 }102 function wasReplacedAlready(fileName: string, target: string) {103 // skipping this import because is has been previously replaced already104 if (replaceRemapping.has(fileName) && replaceRemapping.get(fileName).includes(target)) {105 return true;106 }107 return false;108 }109 function getReplacementPathRelativeToFile(110 currentSourceFile: string,111 referencedSourceFile: string112 ) {113 filesRemapping.set(currentSourceFile, getReplacementPathRelativeToBase(cwd, currentSourceFile));114 filesRemapping.set(115 referencedSourceFile,116 getReplacementPathRelativeToBase(cwd, referencedSourceFile)117 );118 const result = path119 .relative(filesRemapping.get(currentSourceFile), filesRemapping.get(referencedSourceFile))120 .slice(1)121 .replace('.d.ts', '')122 .replace('.ts', '');123 replaceRemapping.set(currentSourceFile, [124 ...(replaceRemapping.get(currentSourceFile) || []),125 result,126 ]);127 return result;128 }129 function wasIgnored(target: string) {130 if (externals.includes(target)) {131 return true;132 }133 return false;134 }135 function replaceImport(node: ts.Node) {136 if (137 (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&138 node.moduleSpecifier !== undefined139 ) {140 // @ts-ignore141 const target: string = node.moduleSpecifier.text;142 let currentSourceFile = '';143 let referencedSourceFile = '';144 if (wasIgnored(target)) {145 return true;146 }147 currentSourceFile = node.getSourceFile().fileName;148 if (wasReplacedAlready(currentSourceFile, target)) {149 return true;150 }151 // find the sourceFile the import is pointing to152 referencedSourceFile = getSourceFile(153 typeChecker.getSymbolAtLocation(node.moduleSpecifier).valueDeclaration154 ).fileName;155 const replacementPath = getReplacementPathRelativeToFile(156 currentSourceFile,157 referencedSourceFile158 );159 // @ts-ignore160 node.moduleSpecifier = ts.createStringLiteral(replacementPath);161 return true;162 }163 if (ts.isImportTypeNode(node)) {164 const target = node.argument.getText().slice(1, -1);165 let currentSourceFile = '';166 let referencedSourceFile = '';167 // check if the import's path is in the ignore-list168 if (wasIgnored(target)) {169 return true;170 }171 currentSourceFile = node.getSourceFile().fileName;172 // check if it's already been replaced previously173 if (wasReplacedAlready(currentSourceFile, target)) {174 return true;175 }176 // find the sourceFile the import is pointing to177 referencedSourceFile = getSourceFile(178 typeChecker.getSymbolAtLocation(node).valueDeclaration179 ).fileName;180 const replacementPath = getReplacementPathRelativeToFile(181 currentSourceFile,182 referencedSourceFile183 );184 // @ts-ignore185 node.argument = ts.createStringLiteral(replacementPath);186 // node.argument = ts.factory.createStringLiteral(replacementPath); // TS4187 return true;188 }189 return undefined;190 }191 function getSourceFile(moduleNode: ts.Node) {192 while (!ts.isSourceFile(moduleNode)) {193 moduleNode = moduleNode.getSourceFile();194 }195 return moduleNode;196 }197 function walkNodeToReplaceImports(node: ts.Node) {198 // it seems that it is unnecessary, but we're sure that it is impossible to have import statement later than we can just skip this node199 if (replaceImport(node)) {200 return;201 }202 ts.forEachChild(node, (n) => walkNodeToReplaceImports(n));203 }204 function outputSourceToFile(sourceFile: ts.SourceFile) {205 const newPath = filesRemapping.get(sourceFile.fileName);206 fs.outputFileSync(newPath, printer.printFile(sourceFile).trim());207 }208 function actOnSourceFile(sourceFile: ts.SourceFile & { resolvedModules?: Map<any, any> }) {209 // console.log(sourceFile);210 filesRemapping.set(211 sourceFile.fileName,212 getReplacementPathRelativeToBase(cwd, sourceFile.fileName)213 );214 walkNodeToReplaceImports(sourceFile);215 outputSourceToFile(sourceFile);216 // using a internal 'resolvedModules' API to get all the modules that were imported by this source file217 // this seems to be a cache TypeScript uses internally218 // I've been looking for a a public API to use, but so far haven't found it.219 // I could create the dependency graph myself, perhaps that'd be better, but I'm OK with this for now.220 if (sourceFile.resolvedModules && sourceFile.resolvedModules.size > 0) {221 Array.from(sourceFile.resolvedModules.entries()).forEach(([k, v]) => {222 // console.log({ k }, v.resolvedFileName);223 if (externals.includes(k)) {224 return;225 }226 const x = sourceFiles.find((f) => f.fileName === v.resolvedFileName);227 if (!x) {228 return;229 }230 if (replaceRemapping.has(v.resolvedFileName)) {231 return;232 }233 actOnSourceFile(sourceFiles.find((f) => f.fileName === v.resolvedFileName));234 });235 }236 }...
Using AI Code Generation
1const { filesRemapping } = require('storybook-root-alias');2module.exports = {3 stories: filesRemapping([4 '../src/**/*.stories.@(js|jsx|ts|tsx)',5 webpackFinal: async (config) => {6 config.resolve.alias = {7 ...filesRemapping(),8 };9 return config;10 },11};12const { filesRemapping } = require('storybook-root-alias');13module.exports = {14 resolve: {15 alias: {16 ...filesRemapping(),17 },18 },19};20{21 "compilerOptions": {22 "paths": {23 }24 }25}26const { filesRemapping } = require('storybook-root-alias');27module.exports = {28 moduleNameMapper: {29 ...filesRemapping(),30 },31};32{33 "babel-plugin-root-import",34 {35 {36 }37 }38}39module.exports = {40 settings: {41 'import/resolver': {42 alias: {43 },44 },45 },46};47module.exports = {48 'import/resolver': {49 alias: {50 },51 },52};53module.exports = {54 settings: {55 'import/resolver': {56 alias: {57 },58 },59 },60};
Using AI Code Generation
1const filesRemapping = require('storybook-root-alias/filesRemapping');2module.exports = {3 stories: ['../src/**/*.stories.@(tsx|mdx)'],4 webpackFinal: async (config) => {5 config.resolve.plugins = config.resolve.plugins.filter(6 (plugin) => plugin.constructor.name !== 'ModuleScopePlugin'7 );8 config.resolve.alias = {9 ...filesRemapping(),10 };11 return config;12 },13};14module.exports = {15 stories: ['../src/**/*.stories.@(tsx|mdx)'],16 webpackFinal: async (config) => {17 config.resolve.plugins = config.resolve.plugins.filter(18 (plugin) => plugin.constructor.name !== 'ModuleScopePlugin'19 );20 config.resolve.alias = {21 ...filesRemapping(),22 };23 return config;24 },25};26import React from 'react';27import { addDecorator } from '@storybook/react';28import { ThemeProvider } from 'styled-components';29import { GlobalStyle } from '../src/styles/GlobalStyle';30import { theme } from '../src/styles/theme';31addDecorator((storyFn) => (32 <ThemeProvider theme={theme}>{storyFn()}</ThemeProvider>33));
Using AI Code Generation
1const { filesRemapping } = require('storybook-root-alias');2filesRemapping();3const { addRootAlias } = require('storybook-root-alias');4addRootAlias('@', 'src');5import { configure } from '@storybook/react';6import { addRootAlias } from 'storybook-root-alias';7addRootAlias('@', 'src');8configure(require.context('../src', true, /\.stories\.js$/), module);9const { addRootAlias } = require('storybook-root-alias');10module.exports = (baseConfig, env, config) => {11 addRootAlias('@', 'src');12 return config;13};14const { addRootAlias } = require('storybook-root-alias');15module.exports = async ({ config, mode }) => {16 addRootAlias('@', 'src');17 return config;18};19const { addRootAlias } = require('storybook-root-alias');20module.exports = async ({ config, mode }) => {21 addRootAlias('@', 'src');22 return config;23};24import { addRootAlias } from 'storybook-root-alias';25addRootAlias('@', 'src');26import { addRootAlias } from 'storybook-root-alias';27addRootAlias('@', 'src');28import { addRootAlias } from 'storybook-root-alias';29addRootAlias('@', 'src');
Using AI Code Generation
1import {configure} from '@storybook/react';2import {filesRemapping} from 'storybook-root-alias';3const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));4function loadStories() {5 req.keys().forEach(req);6}7configure(loadStories, module);8import {configure} from '@storybook/react';9import {filesRemapping} from 'storybook-root-alias';10const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));11function loadStories() {12 req.keys().forEach(req);13}14configure(loadStories, module);15import {configure} from '@storybook/react';16import {filesRemapping} from 'storybook-root-alias';17const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));18function loadStories() {19 req.keys().forEach(req);20}21configure(loadStories, module);22import {configure} from '@storybook/react';23import {filesRemapping} from 'storybook-root-alias';24const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));25function loadStories() {26 req.keys().forEach(req);27}28configure(loadStories, module);29import {configure} from '@storybook/react';30import {filesRemapping} from 'storybook-root-alias';31const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));32function loadStories() {33 req.keys().forEach(req);34}35configure(loadStories, module);36import {configure} from '@storybook/react';37import {filesRemapping} from 'storybook-root-alias';38const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));39function loadStories() {40 req.keys().forEach(req);41}42configure(loadStories, module);
Using AI Code Generation
1').flesRempping;2cont path = require(path'3import { addParameters } from '@storybook/react';4imstorios: filesRematping(p th.resolve(__dirname, '../sr{/**/*.stories.js')),5};6ionstnpath = requireg'path');7 } st frlesRemappino = require('storybook-root').filesRemapping;8module.exports = async ('storybo, modroot-alias';9cng.rolv.las ={10addP...arameters({,11 ...path(__drnme, '../rc'), true,12 };13 alias: {14 },s15const filesRemapping = require('storybook-root').filesRemapping;16cont path = require('path');17 }),18}); filesRemapping(path.resolve(__dirname,')19};20cnt =requir('').fieRsmap ing;21 opst path =Remapping paqhui;e('storybook-root-alias');22module.exports = {module.exports = ({ config }) => {23 stories:cfilesRemapping(pnfi.resolve(__dirname,.'../src/**/*res.l.pssh(')),__dirname);24};25 ': './src',. },26renstrpanhc= reqoirf('pgth');27mo;ule.expr= {28 sries:ileRemapping(pah.esve(__drnme, '../r}/**/*.ories.js')),29}30.stst orlosRemappingk=peequire(wjs-oo).f/lesRe/acping;31conse p ihm=prequiie(mpayho)ot-alias32motule.exp rae'=o{33ora'oris:(pa.rest ve(__dfrnimemap../pia/**/*.stdesjs')),34}35 filesRemapping: filesRemapping({36 aafilesRemsppngot').filesRemapping;37cns pth = requre('pth38 }, {39 toris: ilesRemappn(path.resolv(__dirame'../sr/**/*.stres.js'),40};
Using AI Code Generation
1import/{/addPacamode socfromo'@use filesRrmpio';s2const { filesRemapping } = require('storybook-root-alias');3adParamt({4fileRemappig:lesRemappin({5mol es = :{{6 },7 }),8});9 webpacwebpkcknemyppingc (config => {10 config.resolve.modules.push(__dirname);11 config.resolvs = webpakping({12 ctnfig.res:_ve.modules.push(__ddrnime);13nec,nfg.reslve.=wbpack({14 s: {: {15 },16 }17 },18 });19 return config;20 code}to use webpackRemapping method of storybook-root-alias21import: {Parameters } frm '@strybook/reac';22mport { fileRemapping23,Parameers({24 fleRemapping:fleRemapping({25 alas:{26 },27 }),28});29 filesRemapping: filesRemapping({30cont{ilesReapping } =require()31module.exports = { '@': './src',32 ebpackFinal: syc(cnfig) => {33 config.resolve.modules.ph(__dirnam);34 cong.resov.alia = webpack({35 : {36 },37 };38 }, },39 core {40 },41 aametrs: {42 flRemapping:fileRemapp({43 s: {44 },45 }),46 },47;48const {webpckRem49const { webpackRem
Using AI Code Generation
1import {configure} from '@storybook/react';2import {filesRemapping} from 'storybook-root-alias';3const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));4function loadStories() {5 req.keys().forEach(req);6}7configure(loadStories, module);8import {configure} from '@storybook/react';9import {filesRemapping} from 'storybook-root-alias';10const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));11function loadStories() {12 req.keys().forEach(req);13}14configure(loadStories, module);15import {configure} from '@storybook/react';16import {filesRemapping} from 'storybook-root-alias';17const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));18function loadStories() {19 req.keys().forEach(req);20}21configure(loadStories, module);22import {configure} from '@storybook/react';23import {filesRemapping} from 'storybook-root-alias';24const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));25function loadStories() {26 req.keys().forEach(req);27}28configure(loadStories, module);29import {configure} from '@storybook/react';30import {filesRemapping} from 'storybook-root-alias';31const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));32function loadStories() {33 req.keys().forEach(req);34}35configure(loadStories, module);36import {configure} from '@storybook/react';37import {filesRemapping} from 'storybook-root-alias';38const req = filesRemapping(require.context('../src', true, /\.stories\.js$/));39function loadStories() {40 req.keys().forEach(req);41}42configure(loadStories, module);
Using AI Code Generation
1const { filesRemapping } = require('storybook-root-alias');2module.exports = {3 webpackFinal: async (config, { configType }) => {4 config.resolve.alias = filesRemapping(config.resolve.alias);5 return config;6 },7};8module.exports = {9 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],10 webpackFinal: require('../test'),11};12import { addDecorator } from '@storybook/react';13import { withA11y } from '@storybook/addon-a11y';14addDecorator(withA11y);o use filesRemapping method of storybook-root-alias15const { filesRemapping } = require('storybook-root-alias');16filesRemapping();17const { addRootAlias } = require('storybook-root-alias');18addRootAlias('@', 'src');19import { configure } from '@storybook/react';20import { addRootAlias } from 'storybook-root-alias';21addRootAlias('@', 'src');22configure(require.context('../src', true, /\.stories\.js$/), module);23const { addRootAlias } = require('storybook-root-alias');24module.exports = (baseConfig, env, config) => {25 addRootAlias('@', 'src');26 return config;27};28const { addRootAlias } = require('storybook-root-alias');29module.exports = async ({ config, mode }) => {30 addRootAlias('@', 'src');31 return config;32};33const { addRootAlias } = require('storybook-root-alias');34module.exports = async ({ config, mode }) => {35 addRootAlias('@', 'src');36 return config;37};38import { addRootAlias } from 'storybook-root-alias';39addRootAlias('@', 'src');40import { addRootAlias } from 'storybook-root-alias';41dirname, '../src'));
Using AI Code Generation
1const { filesRemapping } = require('storybook-root-alias');2filesRemapping();3moule.exports = {4 stores: ['../sc/**/*.stories.@(js|jsx|ts|tsx)'],5};6cost { withRootAlias } = require('storybook-root-alias');7const path = require('path');8module.exports = withRootAlias({9 webpackFinal: async (config) => {10 return config;11 },12});13const { withRootAlias } = require('storybook-root-alias');14const path = require('path');15odule.exports = withRootAlias({16 webpackFinal: async (config) => {17 return config;18 }19});20const { withRootAlias } = require('storybook-root-alias);21const path = require('path');22moduleexports = withRootAlias({23 webpackFinal: async (config) => {24 return config;25 },26});27const { withRootAlias } = require('storybook-root-alias;28const path = require('path'29module.exports = withRootAlias({30 webpackFinal: async (config) => {31 },32});33addRootAlias('@', 'src');34import { addRootAlias } from 'storybook-root-alias';35addRootAlias('@', 'src');
Using AI Code Generation
1const { filesRemapping } = require('storybook-root-alias');2module.exports = {3 webpackFinal: async (config, { configType }) => {4 config.resolve.alias = filesRemapping(config.resolve.alias);5 return config;6 },7};8module.exports = {9 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],10 webpackFinal: require('../test'),11};12import { addDecorator } from '@storybook/react';13import { withA11y } from '@storybook/addon-a11y';14addDecorator(withA11y);
Using AI Code Generation
1const path = require('path');2const { filesRemapping } = require('storybook-root-alias');3module.exports = {4 webpackFinal: async config => {5 config.module.rules.push({6 test: /\.(ts|tsx)$/,7 {8 loader: require.resolve('awesome-typescript-loader'),9 },10 {11 loader: require.resolve('react-docgen-typescript-loader'),12 },13 });14 config.resolve.extensions.push('.ts', '.tsx');15 const rootPath = path.resolve(__dirname, '../');16 filesRemapping(config, rootPath);17 return config;18 },19};20{21 "compilerOptions": {22 "paths": {23 }24 }25}26const path = require('path');27const { filesRemapping } = require('storybook-root-alias');28module.exports = async ({ config, mode }) => {29 config.module.rules.push({30 test: /\.(ts|tsx)$/,31 {32 loader: require.resolve('awesome-typescript-loader'),33 },34 {35 loader: require.resolve('react-docgen-typescript-loader'),36 },37 });38 config.resolve.extensions.push('.ts', '.tsx');39 const rootPath = path.resolve(__dirname, '../');40 filesRemapping(config, rootPath);41 return config;42};43module.exports = {44 webpackFinal: async config => {45 config.module.rules.push({46 test: /\.(ts|tsx)$/,47 {48 loader: require.resolve('awesome-typescript-loader'),49 },50 {51 loader: require.resolve('react-docgen-typescript-loader'),52 },53 });
Using AI Code Generation
1const filesRemapping = require('@storybook-root/filesRemapping');2const path = require('path');3const remap = filesRemapping(__dirname, path.resolve(__dirname, '../src'));4const remappedPath = remap('somePath');5console.log(remappedPath);6const filesRemapping = require('@storybook-root/filesRemapping');7const path = require('path');8const remap = filesRemapping(__dirname, path.resolve(__dirname, '../src'));9const remappedPath = remap('somePath');10console.log(remappedPath);11const filesRemapping = require('@storybook-root/filesRemapping');12const path = require('path');13const remap = filesRemapping(__dirname, path.resolve(__dirname, '../src'));14const remappedPath = remap('somePath');15console.log(remappedPath);16const filesRemapping = require('@storybook-root/filesRemapping');17const path = require('path');18const remap = filesRemapping(__dirname, path.resolve(__dirname, '../src'));19const remappedPath = remap('somePath');20console.log(remappedPath);21const filesRemapping = require('@storybook-root/filesRemapping');22const path = require('path');23const remap = filesRemapping(__dirname, path.resolve(__dirname, '../src'));24const remappedPath = remap('somePath');25console.log(remappedPath);26const filesRemapping = require('@storybook-root/filesRemapping');27const path = require('path');28const remap = filesRemapping(__dirname, path.resolve(__dirname, '../src'));
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!