How to use tsConfigJson method in storybook-root

Best JavaScript code snippet using storybook-root

compile-references.js

Source:compile-references.js Github

copy

Full Screen

1// @ts-check2'use-strict';3const cp = require('child_process');4const path = require('path').posix;5const fs = require('fs');6const ROOT = path.join(__dirname, '..');7const DRY_RUN = popFlag(process.argv, '--dry-run');8const FORCE_REWRITE = popFlag(process.argv, '--force-rewrite') && !DRY_RUN;9/** @type {{ [packageName: string]: YarnWorkspace }} */10const YARN_WORKSPACES = JSON.parse(cp.execSync('yarn --silent workspaces info').toString());11// Add the package name inside each package object.12for (const [packageName, yarnWorkspace] of Object.entries(YARN_WORKSPACES)) {13 yarnWorkspace.name = packageName;14}15/** @type {YarnWorkspace} */16const MALAGU_MONOREPO = {17 name: '@malagu/monorepo',18 workspaceDependencies: Object.keys(YARN_WORKSPACES),19 location: ROOT,20};21try {22 let rewriteRequired = false;23 let result = false;24 // Configure all `compile.tsconfig.json` files of this monorepo25 for (const packageName of Object.keys(YARN_WORKSPACES)) {26 const workspacePackage = YARN_WORKSPACES[packageName];27 const tsconfigCompilePath = path.join(ROOT, workspacePackage.location, 'compile.tsconfig.json');28 const references = getTypescriptReferences(workspacePackage);29 result = configureTypeScriptCompilation(workspacePackage, tsconfigCompilePath, references);30 rewriteRequired = rewriteRequired || result;31 }32 // Configure our root compilation configuration, living inside `configs/root-compilation.tsconfig.json`.33 const configsFolder = path.join(ROOT, 'configs');34 const tsconfigCompilePath = path.join(configsFolder, 'root-compilation.tsconfig.json');35 const references = getTypescriptReferences(MALAGU_MONOREPO, configsFolder);36 result = configureTypeScriptCompilation(MALAGU_MONOREPO, tsconfigCompilePath, references);37 rewriteRequired = rewriteRequired || result;38 // Configure the root `tsconfig.json` for code navigation using `tsserver`.39 const tsconfigNavPath = path.join(ROOT, 'tsconfig.json');40 result = configureTypeScriptNavigation(MALAGU_MONOREPO, tsconfigNavPath);41 rewriteRequired = rewriteRequired || result;42 // CI will be able to tell if references got changed by looking at the exit code.43 if (rewriteRequired) {44 if (DRY_RUN) {45 // Running a dry run usually only happens when a developer or CI runs the tests, so we only print the help then.46 console.error('TypeScript references seem to be out of sync, run "yarn prepare:references" to fix.');47 process.exitCode = 1;48 } else {49 console.warn('TypeScript references were out of sync and got updated.');50 }51 }52} catch (error) {53 console.error(error);54 process.exitCode = 1;55}56/**57 * @param {YarnWorkspace} requestedPackage58 * @param {string} [overrideLocation] affects how relative paths are computed.59 * @returns {string[]} project references for `requestedPackage`.60 */61function getTypescriptReferences(requestedPackage, overrideLocation) {62 const references = [];63 for (const dependency of requestedPackage.workspaceDependencies || []) {64 const depWorkspace = YARN_WORKSPACES[dependency];65 const depConfig = path.join(depWorkspace.location, 'compile.tsconfig.json');66 if (!fs.existsSync(depConfig)) {67 continue;68 }69 const relativePath = path.relative(overrideLocation || requestedPackage.location, depWorkspace.location);70 references.push(relativePath);71 }72 return references;73}74/**75 * Wires a given compilation tsconfig file according to the provided references.76 * This allows TypeScript to operate in build mode.77 *78 * @param {YarnWorkspace} targetPackage for debug purpose.79 * @param {string} tsconfigPath path to the tsconfig file to edit.80 * @param {string[]} references list of paths to the related project roots.81 * @returns {boolean} rewrite was needed.82 */83function configureTypeScriptCompilation(targetPackage, tsconfigPath, references) {84 if (!fs.existsSync(tsconfigPath)) {85 return false;86 }87 const tsconfigJson = readJsonFile(tsconfigPath);88 let needRewrite = FORCE_REWRITE;89 if (!tsconfigJson.compilerOptions) {90 // Somehow no `compilerOptions` literal is defined.91 tsconfigJson.compilerOptions = {92 composite: true,93 rootDir: 'src',94 outDir: 'lib',95 };96 needRewrite = true;97 } else if (!tsconfigJson.compilerOptions.composite) {98 // `compilerOptions` is missing the `composite` literal.99 tsconfigJson.compilerOptions = {100 composite: true,101 ...tsconfigJson.compilerOptions,102 };103 needRewrite = true;104 }105 /** @type {string[]} */106 const tsconfigReferences = references107 .map(reference => path.join(reference, 'compile.tsconfig.json'));108 /** @type {string[]} */109 const currentReferences = (tsconfigJson['references'] || [])110 // We will work on a set of paths, easier to handle than objects.111 .map(reference => reference.path)112 // Remove any invalid reference (maybe outdated).113 .filter((referenceRelativePath, index, self) => {114 if (!tsconfigReferences.includes(referenceRelativePath)) {115 // Found a reference that wasn't automatically computed, will remove.116 console.warn(`error: ${targetPackage.name} untracked reference: ${referenceRelativePath}`);117 needRewrite = true;118 return false; // remove119 }120 if (self.indexOf(referenceRelativePath) !== index) {121 // Remove duplicates.122 console.error(`error: ${targetPackage.name} duplicate reference: ${referenceRelativePath}`);123 needRewrite = true;124 return false; // remove125 }126 const referencePath = path.join(path.dirname(tsconfigPath), referenceRelativePath);127 try {128 const referenceStat = fs.statSync(referencePath);129 if (referenceStat.isDirectory() && fs.statSync(path.join(referencePath, 'tsconfig.json')).isFile()) {130 return true; // keep131 } else if (referenceStat.isFile()) { // still could be something else than a tsconfig, but good enough.132 return true; // keep133 }134 } catch {135 // passthrough136 }137 console.error(`error: ${targetPackage.name} invalid reference: ${referenceRelativePath}`);138 needRewrite = true;139 return false; // remove140 });141 for (const tsconfigReference of tsconfigReferences) {142 if (!currentReferences.includes(tsconfigReference)) {143 console.error(`error: ${targetPackage.name} missing reference: ${tsconfigReference}`);144 currentReferences.push(tsconfigReference);145 needRewrite = true;146 }147 }148 if (!DRY_RUN && needRewrite) {149 tsconfigJson.references = currentReferences.map(path => ({ path }));150 const content = JSON.stringify(tsconfigJson, undefined, 2);151 fs.writeFileSync(tsconfigPath, content + '\n');152 console.warn(`info: ${tsconfigPath} updated.`);153 }154 return needRewrite;155}156/**157 * Wire the root `tsconfig.json` to map scoped import to real location in the monorepo.158 * This setup is a shim for the TypeScript language server to provide cross-package navigation.159 * Compilation is done via `compile.tsconfig.json` files.160 *161 * @param {YarnWorkspace} targetPackage for debug purpose.162 * @param {string} tsconfigPath163 * @returns {boolean} rewrite was needed.164 */165function configureTypeScriptNavigation(targetPackage, tsconfigPath) {166 const tsconfigJson = readJsonFile(tsconfigPath);167 let needRewrite = FORCE_REWRITE;168 if (typeof tsconfigJson.compilerOptions === 'undefined') {169 // Somehow no `compilerOptions` literal is defined.170 tsconfigJson.compilerOptions = {171 baseUrl: '.',172 paths: {},173 };174 needRewrite = true;175 } else if (typeof tsconfigJson.compilerOptions.paths === 'undefined') {176 // `compilerOptions` is missing the `paths` literal.177 tsconfigJson.compilerOptions = {178 ...tsconfigJson.compilerOptions,179 paths: {},180 };181 needRewrite = true;182 }183 /** @type {{ [prefix: string]: string[] }} */184 const currentPaths = tsconfigJson.compilerOptions.paths;185 for (const packageName of MALAGU_MONOREPO.workspaceDependencies) {186 const depWorkspace = YARN_WORKSPACES[packageName];187 /** @type {string} */188 let originalImportPath;189 /** @type {string} */190 let mappedFsPath;191 const depSrcPath = path.join(depWorkspace.location, 'src');192 const depConfigPath = path.join(depWorkspace.location, 'compile.tsconfig.json');193 if (fs.existsSync(depConfigPath) && fs.existsSync(depSrcPath)) {194 // If it is a TypeScript dependency, map `lib` imports to our local sources in `src`.195 const depConfigJson = readJsonFile(depConfigPath);196 originalImportPath = `${packageName}/${depConfigJson.compilerOptions.outDir}/*`;197 mappedFsPath = path.relative(MALAGU_MONOREPO.location, path.join(depSrcPath, '*'));198 } else {199 // I don't really know what to do here, simply point to our local package root.200 originalImportPath = `${packageName}/*`;201 mappedFsPath = path.relative(MALAGU_MONOREPO.location, path.join(depWorkspace.location, '*'));202 }203 /** @type {string[] | undefined} */204 const currentFsPaths = currentPaths[originalImportPath];205 if (typeof currentFsPaths === 'undefined' || currentFsPaths.length !== 1 || currentFsPaths[0] !== mappedFsPath) {206 console.error(`error: ${targetPackage.name} invalid mapped path: {"${originalImportPath}": "${currentFsPaths}"}`);207 currentPaths[originalImportPath] = [mappedFsPath];208 needRewrite = true;209 }210 }211 if (!DRY_RUN && needRewrite) {212 const content = JSON.stringify(tsconfigJson, undefined, 2);213 fs.writeFileSync(tsconfigPath, content + '\n');214 console.warn(`info: ${tsconfigPath} updated.`);215 }216 return needRewrite;217}218/**219 *220 * @param {string[]} argv221 * @param {string} flag222 * @returns {boolean}223 */224function popFlag(argv, flag) {225 const flagIndex = argv.indexOf(flag)226 if (flagIndex !== -1) {227 argv.splice(flagIndex, 1);228 return true;229 } else {230 return false;231 }232}233/**234 * @param {string} filePath235 * @returns {any}236 */237function readJsonFile(filePath) {238 try {239 return JSON.parse(fs.readFileSync(filePath).toString());240 } catch (error) {241 console.error('ParseError in file:', filePath);242 throw error;243 }244}245/**246 * @typedef YarnWorkspace247 * @property {string} name248 * @property {string} location249 * @property {string[]} workspaceDependencies...

Full Screen

Full Screen

update-tsconfig-files.ts

Source:update-tsconfig-files.ts Github

copy

Full Screen

1import { join } from 'path'2import type { ProjectConfiguration, Tree } from '@nrwl/devkit'3import { updateJson } from '@nrwl/devkit'4type TSConfigJson = {5 exclude: string[]6 references: { path: string }[]7}8export function updateTsconfigFiles(tree: Tree, projectConfiguration: ProjectConfiguration) {9 // Add reference to tsconfig.json10 updateJson<TSConfigJson, TSConfigJson>(tree, join(projectConfiguration.root, 'tsconfig.json'), (value) => {11 if (!value.references.find(({ path }) => path === './tsconfig.ct.json')) {12 value.references.unshift({ path: './tsconfig.ct.json' })13 }14 return value15 })16 // Exclude cypress/** and **/*.ct.tsx from tsconfig.app.json or tsconfig.lib.json17 const filename = projectConfiguration.projectType === 'application' ? 'tsconfig.app.json' : 'tsconfig.lib.json'18 updateJson<TSConfigJson, TSConfigJson>(tree, join(projectConfiguration.root, filename), (value) => {19 if (!value.exclude.includes('cypress/**')) {20 value.exclude.unshift('cypress/**')21 }22 if (!value.exclude.includes('**/*.ct.tsx')) {23 value.exclude.unshift('**/*.ct.tsx')24 }25 return value26 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const tsConfigJson = require('storybook-root-alias/tsConfigJson');2module.exports = {3 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],4 webpackFinal: async (config) => {5 config.resolve.alias = {6 ...tsConfigJson(),7 };8 return config;9 },10};11{12 "compilerOptions": {13 "paths": {14 }15 }16}17import MyComponent from '@components/MyComponent';18export default function MyComponent() {19 return <div>MyComponent</div>;20}21import MyComponent from '@components/MyComponent';22const path = require('path');23const { rootAlias } = require('storybook-root-alias');24module.exports = {25 resolve: {26 alias: {27 ...rootAlias(),28 },29 },30};31{32 "compilerOptions": {33 "paths": {34 }35 }36}37const { pathsToModuleNameMapper } = require('ts-jest/utils');38const { compilerOptions } = require('./tsconfig.paths.json');39module.exports = {40 moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {41 }),42};43const path = require('path');44const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');45module.exports = {46 resolve: {47 plugins: [new TsconfigPathsPlugin()],48 },49};50const path = require('path');

Full Screen

Using AI Code Generation

copy

Full Screen

1const rootConfig = require('storybook-root-config');2const tsConfig = rootConfig.tsConfigJson();3module.exports = {4 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],5 typescript: {6 reactDocgenTypescriptOptions: {7 propFilter: (prop) => {8 if (prop.parent) {9 return !prop.parent.fileName.includes('node_modules');10 }11 return true;12 },13 },14 tsLoaderOptions: {15 },16 },17};18const rootConfig = require('storybook-root-config');19const tsConfig = rootConfig.tsConfigJson();20module.exports = async ({ config, mode }) => {21 config.module.rules.push({22 test: /\.(ts|tsx)$/,23 {24 loader: require.resolve('awesome-typescript-loader'),25 options: {26 },27 },28 {29 loader: require.resolve('react-docgen-typescript-loader'),30 },31 });32 config.resolve.extensions.push('.ts', '.tsx');33 return config;34};35const rootConfig = require('storybook-root-config');36const tsConfig = rootConfig.tsConfigJson();37module.exports = {38 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],39 typescript: {40 reactDocgenTypescriptOptions: {41 propFilter: (prop) => {42 if (prop.parent) {43 return !prop.parent.fileName.includes('node_modules');44 }45 return true;46 },47 },48 tsLoaderOptions: {49 },50 },51};52const rootConfig = require('storybook-root-config');53const tsConfig = rootConfig.tsConfigJson();54module.exports = async ({ config

Full Screen

Using AI Code Generation

copy

Full Screen

1const tsConfig = require('@storybook/react/dist/server/config/defaults/webpack.config.js').tsConfigJson;2module.exports = {3 webpackFinal: async (config) => {4 return config;5 },6};7module.exports = {8 webpackFinal: async (config) => {9 return config;10 },11 typescript: {12 checkOptions: {},13 reactDocgenTypescriptOptions: {14 propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),15 },16 },17};18import { addDecorator } from '@storybook/react';19import { withThemesProvider } from 'storybook-addon-styled-component-theme';20import { ThemeProvider } from 'styled-components';21import { defaultTheme } from '../src/theme';22const themes = [defaultTheme];23addDecorator(withThemesProvider(themes));24addDecorator((Story) => (25 <ThemeProvider theme={defaultTheme}>26));27import { addParameters } from '@storybook/react';28import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';29import { withThemesProvider } from 'storybook-addon-styled-component-theme';30import { ThemeProvider } from 'styled-components';31import { defaultTheme } from '../src/theme';32const themes = [defaultTheme];33addDecorator(withThemesProvider(themes));34addDecorator((Story) => (35 <ThemeProvider theme={defaultTheme}>36));37addParameters({38 docs: {39 },40});41import { addParameters } from '@storybook/react';42import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';43import { withThemesProvider } from 'storybook-addon-styled-component-theme';

Full Screen

Using AI Code Generation

copy

Full Screen

1const { tsConfigJson } = require('@nrwl/storybook');2module.exports = tsConfigJson();3const { tsConfigJson } = require('@nrwl/storybook');4module.exports = tsConfigJson();5const { tsConfigJson } = require('@nrwl/storybook');6module.exports = tsConfigJson();7const { tsConfigJson } = require('@nrwl/storybook');8module.exports = tsConfigJson();9const { tsConfigJson } = require('@nrwl/storybook');10module.exports = tsConfigJson();11const { tsConfigJson } = require('@nrwl/storybook');12module.exports = tsConfigJson();13const { tsConfigJson } = require('@nrwl/storybook');14module.exports = tsConfigJson();15const { tsConfigJson } = require('@nrwl/storybook');16module.exports = tsConfigJson();17const { tsConfigJson } = require('@nrwl/storybook');18module.exports = tsConfigJson();19const { tsConfigJson } = require('@nrwl/storybook');20module.exports = tsConfigJson();21const { tsConfigJson } = require('@nrwl/storybook');22module.exports = tsConfigJson();23const { tsConfigJson } = require('@nrwl

Full Screen

Using AI Code Generation

copy

Full Screen

1const tsConfigJson = require('@storybook/react/dist/server/config/defaults/tsConfigJson');2const path = require('path');3module.exports = tsConfigJson(path.resolve(__dirname, '../tsconfig.json'));4const tsConfigJson = require('../test');5const path = require('path');6module.exports = {7 webpackFinal: async config => {8 config.module.rules.push({9 test: /\.(ts|tsx)$/,10 include: path.resolve(__dirname, '../'),11 loader: require.resolve('ts-loader'),12 options: {13 },14 });15 config.resolve.extensions.push('.ts', '.tsx');16 return config;17 },18};19I’m using the latest version of Storybook (5.1.11) and I’m still getting the same error. I tried the solutions above and nothing worked. Any ideas?20{21 "compilerOptions": {22 "paths": {23 },24 }25}26I was able to solve this issue by changing the import in the .storybook/config.js file to:27import '../src/index.css';

Full Screen

Using AI Code Generation

copy

Full Screen

1const { tsConfigJson } = require('@nrwl/react/plugins/storybook');2module.exports = tsConfigJson({});3{4 "compilerOptions": {5 "paths": {6 }7 },8}9{10 "compilerOptions": {11 },12}13{14 "compilerOptions": {15 },16}17{18 "compilerOptions": {19 },20}21{22 "compilerOptions": {23 },24}25{26 "compilerOptions": {27 },

Full Screen

Using AI Code Generation

copy

Full Screen

1const tsConfigJson = require('@storybook/react/dist/server/config/defaults/tsConfig.json');2const tsConfig = require('./tsconfig.json');3module.exports = {4 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],5 webpackFinal: async (config) => {6 config.module.rules.push({7 test: /\.(ts|tsx)$/,8 {9 loader: require.resolve('babel-loader'),10 options: {11 presets: [['react-app', { flow: false, typescript: true }]],12 },13 },14 {15 loader: require.resolve('react-docgen-typescript-loader'),16 options: {17 tsconfigPath: path.resolve(__dirname, '../tsconfig.json'),18 },19 },20 });21 config.resolve.extensions.push('.ts', '.tsx');22 return config;23 },24};25{26 "compilerOptions": {27 },28}29{30 "compilerOptions": {

Full Screen

Using AI Code Generation

copy

Full Screen

1const tsConfigJson = require('@storybook/react/dist/server/config/defaults/webpack.config.js');2const tsConfig = tsConfigJson.default.module.rules[0].options;3module.exports = {4 module: {5 {6 test: /\.(ts|tsx)$/,7 path.resolve(__dirname, '../src'),8 path.resolve(__dirname, '../stories')9 {10 loader: require.resolve('awesome-typescript-loader'),11 options: {12 configFileName: path.resolve(__dirname, '../tsconfig.json'),13 getCustomTransformers: () => ({14 before: [tsImportPluginFactory(tsConfig)]15 })16 }17 },18 { loader: require.resolve('react-docgen-typescript-loader') }19 }20 }21};22module.exports = {23 webpackFinal: config => {24 config.resolve.extensions.push('.ts', '.tsx');25 return config;26 }27};28import { addParameters, addDecorator } from '@storybook/react';29import { withA11y } from '@storybook/addon-a11y';30import { withKnobs } from '@storybook/addon-knobs/react';31import { withInfo } from '@storybook/addon-info';32addDecorator(withA11y);33addDecorator(withKnobs);34addDecorator(withInfo);

Full Screen

Using AI Code Generation

copy

Full Screen

1const tsConfigPath = tsConfigJson();2module.exports = {3 module: {4 {5 {6 options: {7 },8 },9 },10 },11};12const { tsConfigJson } = require('@storybook/react/dist/server/config/utils');13module.exports = async ({ config }) => {14 config.module.rules.push({15 {16 options: {17 configFile: tsConfigJson(),18 },19 },20 });21 return config;22};23const { tsConfigJson } = require('@storybook/react/dist/server/config/utils');24module.exports = {25 webpackFinal: async (config) => {26 config.module.rules.push({27 {28 options: {29 configFile: tsConfigJson(),30 },31 },32 });33 return config;34 },35};36module.exports = {37 webpackFinal: async (config) => {38 config.module.rules.push({39 {40 options: {41 configFile: require.resolve('../tsconfig.json'),42 },43 },44 });45 return config;46 },47};48module.exports = {49 webpackFinal: async (config) => {50 config.module.rules.push({51 {52 options: {53 configFile: tsConfigJson(),54 },55 },56 });57 return config;58 },59};60module.exports = {

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = require('@nrwl/react/plugins/with-storybook').tsConfigJson();2module.exports = {3 webpackFinal: async (config, { configType }) => {4 config.module.rules.push({5 include: path.resolve(__dirname, '../'),6 });7 return config;8 },9 typescript: require('./test.js'),10};11import { addDecorator, addParameters } from '@storybook/react';12import { withKnobs } from '@storybook/addon-knobs';13import { withA11y } from '@storybook/addon-a11y';14import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';15addDecorator(withKnobs);16addDecorator(withA11y);17addParameters({18 viewport: {19 },20});21const path = require('path');22module.exports = async ({ config, mode }) => {23 config.module.rules.push({24 test: /\.(ts|tsx)$/,25 {26 loader: require.resolve('ts-loader'),27 },28 {29 loader: require.resolve('react-docgen-typescript-loader'),30 },31 });32 config.resolve.extensions.push('.ts', '.tsx');33 return config;34};35{36 "compilerOptions": {37 "paths": {

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful