Storybook: I can not import with absolute path in Storybook

Created on 24 Jul 2018  Β·  25Comments  Β·  Source: storybookjs/storybook

Version

  • @storybook/addon-actions: 3.4.8
  • @storybook/addon-links: 3.4.8
  • @storybook/addon-storyshots: 3.4.8
  • @storybook/addons: 3.4.8
  • @storybook/react: 3.4.8
  • React: 16.4.2
  • TypeScript: 2.9.2

Behavior

An error will be displayed in storybook when creating the following components.

# src/components/organisms/ParentComponent/index.tsx
import * as React from 'react';
import ChildrenComponent from 'src/components/molecules/ChildrenComponent/index';

const ParentComponent: React.SFC<{}> = ({ ...props }) => (
  <ChildrenComponent />
);

Error
Module not found: Error: Can't resolve 'src/components/molecules/ChildrenComponent/index' in '/AppRoot/src/components/organisms/ParentComponent'

This seems to be caused by loading with an absolute path, so if you do the following it works fine.
import ChildrenComponent from '../../molecules/ChildrenComponent/index';

However, I would like to avoid this method as much as possible. Is there no way to start storybook without errors other than specifying by relative path?

The application of the absolute path is based on the following description of tsconfig.json.

"compilerOptions": {
  "outDir": "build/dist",
  "rootDir": "src",
  "baseUrl": "."
}

Also, this time we are importing a stories file written in tsx extension in compiled src directory rather than compiled build/dist directory on storybook this time.

This is set in ./storybook/config, but setting it tobuild/dist will produce similar results.

Since this project uses atomic design, it has roughly the following directory structure.

src
β”œβ”€β”€ components
β”‚    β”œβ”€β”€ molecules
β”‚    β”‚   β”œβ”€β”€ ChildrenComponent
β”‚    β”‚   β”‚   β”œβ”€β”€ index.tsx
β”‚    β”‚   β”‚   └── index.stories.tsx
β”‚    β”œβ”€β”€ organisms
β”‚    β”‚   β”œβ”€β”€ ParentComponent
β”‚    β”‚   β”‚   β”œβ”€β”€ index.tsx
β”‚    β”‚   β”‚   └── index.stories.tsx

Related issues

There seemed to be something like the relevant issue.
However, it did not reach a solution.

333 , #3438

Digression

As an aside, I believe there are two ways to solve this problem.

The first thing I would like to ask here is to "Import absolute path component with storybook", the The second is to compile to a js file which imports the importedtsx file with an absolute path as a relative path. After that, apply the imported js file with the relative path to storybook.

Regarding the latter, I think it is not appropriate to listen to this problem here, but if you know it, I would like to ask about that method as well.

Thanks for your time.

react question / support typescript

Most helpful comment

In case anyone is looking at this for storybook 5,

const path = require('path');

module.exports = ({ config }) => {
  config.resolve.modules.push(path.resolve(__dirname, "../src"));
  return config;
};

All 25 comments

I don't know how does it work for you in your regular app (like what is your setup ?), but if you will put your cwd (assuming -> cwd/src/components/.... ) to the resolve.modules in the extended webpack.config, it should probably solve your problem (I've checked it with an Angular app though, but it does not really matter)

My .storybook/webpack.config.js file is described as follows.
Is there a problem here?

const genDefaultConfig = require('@storybook/react/dist/server/config/defaults/webpack.config.js');

module.exports = (baseConfig, env) => {
    const config = genDefaultConfig(baseConfig, env);

    config.module.rules.push({
        test: /\.(ts|tsx)?$/,
        exclude: /node_modules/,
        include: [/stories/, /src/],
        loader: 'ts-loader'
    });
    config.resolve.extensions.push('.ts', '.tsx');

    return config;
};

Try adding something like this:

const path = require('path');

// blah blah code

module.exports = (baseConfig, env) => {

  // blah blah code

  config.resolve.modules = [
    ...(config.resolve.modules || []),
    path.resolve('./'),
  ];
}

It worked properly!!
I cannot thank you enough!!!!!!!

u-r-welcome

@igor-dv I am having a similar issue, and have tried your suggestion (above), as well as the NormalModuleReplacementPlugin which modifies the resource.request path. Neither have worked

Do you have any other suggestions?

Can you please share your code examples / webpack.config.js ?

.storybook/webpack.config.js

const path =require('path');`
// const webpack = require('webpack');
const genDefaultConfig = require('@storybook/react/dist/server/config/defaults/webpack.config.js');

module.exports = (baseConfig, env) => {
const config = genDefaultConfig(baseConfig, env);
config.module = {
rules: [
{
test: /.tsx$/,
loaders: ["ts-loader"],
include: path.resolve(__dirname, '../app/xv/')
},
{
test: /.scss$/,
loaders: [
'style-loader',
'css-loader',
'sass-loader?includePaths[]=' + encodeURIComponent(path.resolve(__dirname, '../app/'))
]
},
{
test: /.css$/,
loader: 'style-loader!css-loader'
},
{
test: /.less$/,
loader: 'style-loader!css-loader!less-loader'
},
{
test: /.js|.ts$/,
exclude: [path.join(__dirname, 'app/components'), /node_modules/],
loader: 'ng-annotate-loader'
},
{
test: /.js$/,
exclude: [path.join(__dirname, 'app/components'), /node_modules/],
loader: 'babel-loader?presets[]=es2015&presets[]=stage-1&presets[]=react&cacheDirectory'
}
]
};

config.resolve.modules = [
    ...(config.resolve.modules || []),
    path.resolve('./'),
];

return config;
// ,
// plugins: [
//     new webpack.NormalModuleReplacementPlugin(/xv/, function(resource) {
//         resource.request = resource.request.includes('xv/') ? '../../app/' + resource.request : resource.request;
//     })
// ]

}`

// code

`import * as React from 'react';

import { autobind } from 'xv/util/decorators';

import '../styles/ActionIcon.scss';`

// error

`ERROR in ./app/xv/ui/components/ActionIcon.tsx

Module not found: Error: Can't resolve 'xv/util/decorators' in '/Users/lukasanderson/workspace/NeXgen-UI/app/xv/ui/components'

@ ./app/xv/ui/components/ActionIcon.tsx 31:0-46
@ ./.storybook/stories/actionIcons.js
@ ./.storybook/config.js
@ multi ./node_modules/@storybook/react/dist/server/config/polyfills.js ./node_modules/@storybook/react/dist/server/config/globals.js (webpack)-hot-middleware/client.js?reload=true ./.storybook/config.js`

with /xv/ being mapped to the base of the project (root/app/xv/*) in the usual webpack dev (non storybook) build

sorry for the formatting

I've tried different variations of the regex replacement with NormalModuleReplacementPlugin, some found in similar threads/issues about storybook not handling absolute paths

example:

plugins: [ new webpack.NormalModuleReplacementPlugin(/xv/, function(resource) { resource.request = resource.request.replace(/xv/, '../../app/'); }) ]

gives me this error:

`ERROR in ./.storybook/stories/actionIcons.js

Module not found: Error: Can't resolve '../../app//ui/components/Tooltip' in '/Users/lukasanderson/workspace/NeXgen-UI/.storybook/stories'

@ ./.storybook/stories/actionIcons.js 5:0-47
@ ./.storybook/config.js
@ multi ./node_modules/@storybook/react/dist/server/config/polyfills.js ./node_modules/@storybook/react/dist/server/config/globals.js (webpack)-hot-middleware/client.js?reload=true ./.storybook/config.js
`

and this change (adding /xv/ to the replacement string)

plugins: [ new webpack.NormalModuleReplacementPlugin(/xv/, function(resource) { resource.request = resource.request.replace(/xv/, '../../app/xv/'); }) ]

gives

`ERROR in ./.storybook/stories/actionIcons.js

Module not found: Error: Can't resolve '../../app/xv//ui/components/Tooltip' in '/Users/lukasanderson/workspace/NeXgen-UI/.storybook/stories'

@ ./.storybook/stories/actionIcons.js 5:0-47
`

when I have the correct path replacement for absolute paths, not only are the relative paths messed up, but the path is 'correct' and an error persists:

ERROR in ./.storybook/stories/actionIcons.js Module not found: Error: Can't resolve '../../app/xv/ui/components/Tooltip' in '/Users/lukasanderson/workspace/NeXgen-UI/.storybook/stories'

What is your working directory (cwd)?

root/

  • .storybook
  • app
    -- xv
    ---ui
    ----components
    ---utils

I start storybook from NeXgen-UI (aka project root)

So having this import { autobind } from 'xv/util/decorators'; you should probably add path.resolve('./app') to the resolve.modules

alright, so I now have this

`
config.resolve = {

    modules: [

        ...(config.resolve.modules || []),

        path.resolve('./app'),

        path.resolve('./')

    ]
};

return config;

`

and am getting the same:

`ERROR in ./app/xv/ui/components/ActionIcon.tsx

Module not found: Error: Can't resolve 'xv/util/decorators' in '/Users/lukasanderson/workspace/NeXgen-UI/app/xv/ui/components'
`

Looks like you need to add config.resolve.extensions.push('.ts', '.tsx'); as well

@igor-dv I gave that a go as well, same error. Thanks for the help on this

πŸ€” I think I need to see the reproduction, then. Do you have a public repo?

For me, it worked by adding __dirname to path.resolve in my webpack config, like this: (I'm working on a create-react-app + TypeScript setup):

config.resolve.modules = [
  ...(config.resolve.modules || []),
  path.resolve(__dirname, "../"),
  path.resolve(__dirname, "../src")
];

My file structure, adjust yours accordingly:

```
/root
/.storybook
webpack.config.js
/src

The stupid thing I failed to realise is I forgot to add a leading ../ to my resolve.modules config.

Here's what works for me:

// .storybook/webpack.config.js
module.exports = {
  ...,
  resolve: {
    modules: [path.resolve(__dirname, "../src"), "node_modules"],
  }
}

This is because my storybook webpack config is located 1 directory deeper in the default .storybook dir.

In case anyone is looking at this for storybook 5,

const path = require('path');

module.exports = ({ config }) => {
  config.resolve.modules.push(path.resolve(__dirname, "../src"));
  return config;
};

You beautiful person @kexinlu1121. It worked perfectly, thank you.

@glocore's solution was the hint I needed for it to work. Thanks!

I had similar issue where my absolute import works in start-storybook but not when I build. I'll just put it here for reference if someone wants some reference.

I'm using @src for absolute import and made it work by adding this line:

# /root/.storybook/webpack.config.js

const path = require("path");

module.exports = ({ config }) => {
  // ...

  // Add absolute path.resolve so storybook can handle absolute import (eg. @src/resources/...)
  config.resolve.alias = {
    ...config.resolve.alias,
    "@src": path.resolve(__dirname, "../src"),
  };

  return config;
};

For context, my project directory looks like this:

/root
  .storybook/
    webpack.config.js
  src/
    components/

Hope it helps :)

@wzulfikar Thank your for your solution!

I got this issue after using CLI and I was able to resolve it by modifying my .storybook/main.js to:

const path = require('path');

module.exports = {
  ...other settings....,

  webpackFinal: async (config) => {
    config.resolve.modules = [
      ...(config.resolve.modules || []),
      path.resolve(__dirname, "../src"),
    ];

    return config;
  },

}

Hello
I'm using React/TS
I got the same issue my .storybook/main.js:

const path = require('path');

module.exports = {
  "stories": [
    "../src/**/*.stories.mdx",
    "../src/**/*.stories.@(js|jsx|ts|tsx)"
  ],
  "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/preset-create-react-app",
    "@storybook/addon-knobs",
  ],
  webpackFinal: async (config) => {

    config.resolve.alias = {
      ...config.resolve.alias,
      'fs': path.resolve(__dirname, 'fsMock.js'),
      'child_process': path.resolve(__dirname, 'fsMock.js'),
      'net': path.resolve(__dirname, 'fsMock.js'),
      'tls': path.resolve(__dirname, 'fsMock.js'),
      // "src/types": path.resolve(__dirname, "../src/types"),
      // "src/components": path.resolve(__dirname, "../src/components"),
    };

    config.resolve.modules = [
      ...(config.resolve.modules || []),
      path.resolve(__dirname, "../src"),
    ];

    // config.resolve.extensions.push('.ts', '.tsx');

    return config;
  },
}

my structure

.storybook
src
β”œβ”€β”€ components
|     index.ts
β”‚   β”œβ”€β”€ ChildrenComponent
β”‚    β”‚  β”œβ”€β”€ index.tsx
β”‚    β”‚  └── index.stories.tsx
β”‚   β”œβ”€β”€ ParentComponent
β”‚    β”‚    β”œβ”€β”€ index.tsx
β”‚    β”‚    └── index.stories.tsx
β”œβ”€β”€ stories

A ParentComponent component

import React from "react";
import { ChildrenComponent } from "src/components";
import { ItemType } from "src/types";

export default ({ item }: { item: ItemType }) => {
  return (
    <p className="hello">
      <ChildrenComponent type={item.type} />
      <span className="ellipsis">{item.title}</span>
    </p>
  );
};

The problem come from src/components because is I do src/components/ChildrenComponent it works.

I don't get it I tried everything here and #333 #3291 and many others

A screen shot of the error
image

Can anyone help ?

Was this page helpful?
0 / 5 - 0 ratings