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 }...
util.ts
Source:util.ts
1'use strict';2export function formatPath(contractPath: string) {3 return contractPath.replace(/\\/g, '/');4}5/**6 * Replaces remappings in the first array with matches from the second array,7 * then it concatenates only the unique strings from the 2 arrays.8 *9 * It splits the strings by '=' and checks the prefix of each element10 * @param remappings first array of remappings strings11 * @param replacer second array of remappings strings12 * @returns an array containing unique remappings13 */14export function replaceRemappings(remappings: string[], replacer: string[]): string[] {15 remappings.forEach(function (remapping, index) {16 const prefix = remapping.split('=')[0];17 for (const replaceRemapping of replacer) {18 const replacePrefix = replaceRemapping.split('=')[0];19 if (prefix === replacePrefix) {20 remappings[index] = replaceRemapping;21 break;22 }23 }24 });25 return [...new Set([...remappings, ...replacer])];...
Using AI Code Generation
1module.exports = {2};3const path = require('path');4const webpack = require('webpack');5const { getLoader } = require('react-app-rewired');6const rewireReactHotLoader = require('react-app-rewire-hot-loader');7const rewireStyledComponents = require('react-app-rewire-styled-components');8const rewiredConfig = (config, env) => {9 const fileLoader = getLoader(10 rule => rule.loader && rule.loader.indexOf(`file-loader`) != -111 );12 fileLoader.exclude.push(/\.svg$/);13 config.module.rules.push({14 {15 },16 {17 options: {18 },19 },20 });21 config.module.rules.push({22 loaders: [require.resolve('@storybook/addon-storysource/loader')],23 });24 config.resolve.alias = {25 '@': path.resolve(__dirname, '../src'),26 };27 return config;28};29module.exports = rewiredConfig;
Using AI Code Generation
1import { replaceRemapping } from 'storybook-root-alias';2replaceRemapping();3import { withStorybookRootAlias } from 'storybook-root-alias';4module.exports = withStorybookRootAlias(module.exports);5module.exports = {6 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],7};8const path = require('path');9const rootAlias = require('storybook-root-alias');10module.exports = async ({ config }) => {11 config.resolve.alias = {12 ...rootAlias.webpackAlias(),13 };14 config.resolve.modules.push(path.resolve(__dirname, '..'));15 return config;16};17{18 "compilerOptions": {19 "paths": {20 }21 }22}23"scripts": {24},25"devDependencies": {26}27{28 "compilerOptions": {29 "paths": {30 }31 }32}33import { withStorybookRootAlias } from 'storybook-root-alias';34module.exports = withStorybookRootAlias(module.exports);35import { withStorybookRootAlias } from 'storybook-root-alias';36module.exports = withStorybookRootAlias(module.exports);37import { withStorybookRootAlias } from 'storybook-root-alias';38module.exports = withStorybookRootAlias(module.exports);39import { withStorybookRootAlias } from
Using AI Code Generation
1const path = require('path');2const { replaceRemapping } = require('storybook-root-alias');3replaceRemapping({4});5module.exports = {6};7module.exports = {8 {9 options: {10 babel: async (options) => {11 const path = require('path');12 const { replaceRemapping } = require('storybook-root-alias');13 replaceRemapping({14 });15 return options;16 },17 },18 },19};
Using AI Code Generation
1const { replaceRemapping } = require('storybook-root-alias');2replaceRemapping();3const req = require.context('../src/components', true, /\.stories\.js$/);4function loadStories() {5 req.keys().forEach(filename => req(filename));6}7configure(loadStories, module);8const { getLoader, loaderByName } = require('@craco/craco');9const path = require('path');10module.exports = ({ config }) => {11 config.resolve.alias['storybook-root-alias'] = path.join(12 );13 const babelLoader = getLoader(14 rule => rule.loader && rule.loader.includes('babel-loader')15 );16 babelLoader.options.plugins.push('babel-plugin-root-import');17 return config;18};19const path = require('path');20module.exports = {21 '@': path.resolve(__dirname, '../src/'),22 '@components': path.resolve(__dirname, '../src/components/'),23 '@containers': path.resolve(__dirname, '../src/containers/'),24 '@pages': path.resolve(__dirname, '../src/pages/'),25 '@utils': path.resolve(__dirname, '../src/utils/'),26};
Using AI Code Generation
1import { replaceRemapping } from 'storybook-root-alias'2replaceRemapping({3})4const { replaceRemapping } = require('storybook-root-alias')5replaceRemapping({6})7const { replaceRemapping } = require('storybook-root-alias')8const path = require('path')9module.exports = async ({ config, mode }) => {10 replaceRemapping({11 })12 config.module.rules.push({13 test: /\.(ts|tsx)$/,14 include: path.resolve(__dirname, '../'),15 {16 loader: require.resolve('ts-loader'),17 },18 {19 loader: require.resolve('react-docgen-typescript-loader'),20 },21 })22 config.resolve.extensions.push('.ts', '.tsx')23}24const { replaceRemapping } = require('storybook-root-alias')25const path = require('path')26module.exports = async ({ config, mode }) => {27 replaceRemapping({28 })29 config.module.rules.push({30 options: {31 loaders: {32 },33 },34 })35 config.resolve.extensions.push('.ts', '.tsx')36}37const { replaceRemapping } = require('storybook-root-alias')38const path = require('path')39module.exports = async ({ config, mode }) => {40 replaceRemapping({41 })42 config.module.rules.push({43 {
Using AI Code Generation
1import { replaceRemapping } from 'storybook-root-alias';2replaceRemapping();3import Button from 'components/atoms/Button';4import Button from '../../../components/atoms/Button';5import Button from '../../../../components/atoms/Button';6import Button from 'components/atoms/Button';7import Button from '../../../components/atoms/Button';8import Button from '../../../../components/atoms/Button';9import Button from 'components/atoms/Button';10import Button from '../../../components/atoms/Button';11import Button from '../../../../components/atoms/Button';12import Button from 'components/atoms/Button';13import Button from '../../../components/atoms/Button';14import Button from '../../../../components/atoms/Button';15import Button from 'components/atoms/Button';16import Button from '../../../components/atoms/Button';17import Button from '../../../../components/atoms/Button';18import Button from 'components/atoms/Button';19import Button from '../../../components/atoms/Button';20import Button from '../../../../components/atoms/Button';21import Button from 'components/atoms/Button';22import Button from '../../../components/atoms/Button';23import Button from '../../../../components/atoms/Button';24import Button from 'components/atoms/Button';25import Button from '../../../components/atoms/Button';26import Button from '../../../../components/atoms/Button';27import Button from 'components/atoms/Button';28import Button from '../../../components/atoms/Button';
Using AI Code Generation
1import { replaceRemapping } from 'storybook-root-alias';2replaceRemapping('@', '../src');3module.exports = {4};5const path = require('path');6const rootAlias = require('storybook-root-alias');7module.exports = async ({ config }) => {8 config.resolve.alias = {9 ...rootAlias.webpackAlias(),10 };11 return config;12};13{14 "compilerOptions": {15 "paths": {16 }17 }18}19Next, import the addon in your .storybook/main.js file:20module.exports = {21};22Then, import the knob functions in your storybook stories:23import { text, boolean, number, select } from '@storybook/addon-knobs';24export default {25};26export const test = () => {27 const name = text('Name', 'John Doe');28 const age = number('Age', 44);29 const content = `I am ${name} and I'm ${age} years old.`;30 return <div>{content}</div>;31};
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!!