Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Module parse failed: You may need an appropriate loader to handle this file type #1493

Closed
dmmarmol opened this issue Jul 19, 2017 · 69 comments
Closed

Comments

@dmmarmol
Copy link

dmmarmol commented Jul 19, 2017

Sorry if this is an already answered issue but trust me when i told you that i spend most of the day googling about this and couldn't find a solution.

I have an existing project (with custom webpack.config.dev.js file) that I want to integrate with storybooks but after following the getting started guide and installing whatever babel or any other kind of dependency available on the web, i'm still not able to overcome this annoing issue.

Module parse failed: ...\src\components\form\button\index.stories.js Unexpected token (10:2) 
You may need an appropriate loader to handle this file type. | storiesOf('Button', module)
 | .add('with text', () => (
 | <Button onClick={action('clicked')}>Hello Button</Button>
 | ))
 | .add('with some emoji', () => (
    at Object.<anonymous> (http://localhost:3001/static/preview.bundle.js:45665:7)
    at __webpack_require__ (http://localhost:3001/static/preview.bundle.js:1203:30)
    at fn (http://localhost:3001/static/preview.bundle.js:731:20)
    at webpackContext (http://localhost:3001/static/preview.bundle.js:45646:9)
    at req.keys.forEach (http://localhost:3001/static/preview.bundle.js:42662:35)
    at Array.forEach (<anonymous>)
    at loadStories (http://localhost:3001/static/preview.bundle.js:42662:13)
    at ConfigApi._renderMain (http://localhost:3001/static/preview.bundle.js:43739:20)
    at render (http://localhost:3001/static/preview.bundle.js:43765:17)
    at ConfigApi.configure (http://localhost:3001/static/preview.bundle.js:43790:9)

Based on the error message i think it has something to do with the configuration in .babelrc. This is my actual setup

Package.json

"scripts": {
    "storybook": "start-storybook -p 3001 -c ./config/.storybook",
    "build-storybook": "build-storybook"
  }

Config dir

Located in ./config/.storybook

./config/.storybook/
- .babelrc
- config.js
- webpack.config.dev.js

.babelrc

(I installed almost EVERYTHING I found related to babel)

{
	"presets": ["es2015", "react", "stage-0"],
	"plugins": [
		"transform-runtime",
		"transform-decorators-legacy",
		"transform-class-properties",
	  	"transform-object-rest-spread",
		"react-hot-loader/babel",
		"typecheck",
  		"transform-es2015-modules-commonjs",
		"add-module-exports",
		"import-asserts"
	]
}

config.js

// Try to load stories from inside the `../../src/` dir where there are the components
const req = require.context('../../src', true, /(\.stories\.js$)|(\.stories\.jsx$)/);
function loadStories() {
	req.keys().forEach((filename) => req(filename));
}
configure(loadStories, module);

webpack.config.dev.js

I'm trying to use the original webpack.config.dev.js file that I setup for my project development

var path = require('path');
var webpack = require('webpack');
var config = require('../webpack.config.dev.js');
module.exports = {
	plugins: [
		new webpack.NoErrorsPlugin(),
		new webpack.HotModuleReplacementPlugin()
	],
	module: {
		loaders: [
			// Transform all ES6 files to plain old ES5.
			{
				test: /\.(js|jsx)$/,
				exclude: [/bower_components/, /node_modules/, /styles/],
				loader: 'babel',
				include: path.resolve(__dirname, '../src')
			},
			// Fonts
			{
				test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
				loader: 'url-loader?limit=10000&mimetype=application/font-woff',
				query: {
					name: 'static/media/files/[name].[hash:8].[ext]'
				}
			}, {
				test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
				loader: 'file-loader',
				query: {
					name: 'static/media/fonts/[name].[hash:8].[ext]'
				}
			},
			// Load images.
			{
				test: /\.(gif|jpe?g|png)$/,
				loader: 'url-loader?limit=25000',
				query: {
					limit: 10000,
					name: 'static/media/images/[name].[hash:8].[ext]'
				}
			},
			// jSon Loader
			{
				test: /\.json$/,
				loader: 'json-loader'
			}, {
				test: /\.scss$/,
				loader: 'style!css!sass!resolve-url!sass?sourceMap&sourceComments'
			}, {
				test: /\.css$/,
				loader: 'style!css?importLoaders=1'
			}
		]
	}
};

Story file

And finally the story file

import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';

// Component
import { Button } from './index';

storiesOf('Button', module)
	.add('with text', () => (
		<Button onClick={action('clicked')}>Hello Button</Button>
	))
	.add('with some emoji', () => (
		<Button onClick={action('clicked')}>😀 😎 👍 💯</Button>
	));
@ecce-domo
Copy link

Just to be clear, are you using two webpack configs? Did you add the loaders to both?

@dmmarmol
Copy link
Author

dmmarmol commented Jul 20, 2017 via email

@dmmarmol
Copy link
Author

dmmarmol commented Jul 20, 2017

@dsiaudvytis This is the other webpack config file only for storybooks

var path = require('path');
var webpack = require('webpack');

var config = require('../webpack.config.dev.js'); // Getting the original webpack.config
var Loaders = require('../webpack.loaders.js'); // Getting the same loaders that I use for the original config file

module.exports = {
	plugins: [
		new webpack.NoErrorsPlugin(),
		new webpack.HotModuleReplacementPlugin()
	],
	module: {
		loaders: Loaders.concat([
			{
				test: /\.scss$/,
				loader: 'style!css!sass!resolve-url!sass?sourceMap&sourceComments'
			},
			{
				test: /\.css$/,
				loader: 'style!css?importLoaders=1'
			}
		])
	}
};

@ecce-domo
Copy link

I think you might need to add the /\.(js|jsx)$/ loader into that storybook webpack config as well.

@ecce-domo
Copy link

I suspect the line var config = require('../webpack.config.dev.js'); doesn't really do anything.

@TheoryOfNekomata
Copy link

Same problem. I have CRA 1.3.3 and getstorybook 3.2.3. Didn't fiddle with webpack configs whatsoever. Oddly enough, it shows React app instead of Create React App when getstorybook is run (because getstorybook looks under devDependencies, not on dependencies for react-scripts, which CRA does install react-scripts under dependencies now).

I tried:

  1. Making a webpack config in .storybook and just requiring CRA's webpack dev config
  2. Copying the whole CRA's webpack dev config and modifying them as to not use require() in loaders
  3. Creating a .babelrc file inside .storybook
  4. Creating a .babelrc file in the project root

None of which worked. Maybe getstorybook is hardwired to use its custom webpack config's loaders?

@dbrrt
Copy link

dbrrt commented Aug 12, 2017

+1, I've got the same issue

@Hypnosphi
Copy link
Member

@Temoto-kun how exactly does the error look in your case?
@dbrtt same question for you

@TheoryOfNekomata
Copy link

@Hypnosphi it's exactly the same error as OP. Apparently, storybook's webpack is unable to transpile JSX because somehow the configs don't work.

@Hypnosphi
Copy link
Member

Can you please create a GitHub repo with minimal reproduction of your issue?

@dbrrt
Copy link

dbrrt commented Aug 19, 2017

@Hypnosphi I replicated the example from storybook usage with Webpack, so another webpack.config.js and it worked (and still works)

@TheoryOfNekomata
Copy link

@Hypnosphi here it is: https://github.com/Temoto-kun/create-react-app-storybook-repro

What I did is I only ran create-react-app and getstorybook to initialize. Both generators' versions are the same from my report.

@Hypnosphi
Copy link
Member

Hypnosphi commented Aug 19, 2017

@Temoto-kun

That's weird. I cloned your repo and I can start storybook with no errors. I tried it with yarn:

yarn
yarn storybook

And with npm 3 and 5:

npm install
npm run storybook

start script doesn't seem to work though, as you're missing CRA's public directory:

$ npm start

> create-react-app-storybook-repro@0.1.0 start /Users/jetbrains/IdeaProjects/create-react-app-storybook-repro
> react-scripts start

Could not find a required file.
  Name: index.html
  Searched in: ~/create-react-app-storybook-repro/public

@TheoryOfNekomata
Copy link

Maybe because of Node then? I have 7.7.1.

And BTW I'm also running Windows 10.

Any other info I can provide?

@Hypnosphi
Copy link
Member

Hypnosphi commented Aug 20, 2017

Works for me with node v7.7.1 on mac. Will test on Windows.

Node that node 7 has reached end of support this June

UPD: works for me on Win10 with node v7.7.1 as well

@TheoryOfNekomata
Copy link

Tried updating my Node to 8.4.0. Still didn't work.

@dbrrt
Copy link

dbrrt commented Aug 20, 2017

@Temoto-kun Is you error message still the same ?

@igor-dv
Copy link
Member

igor-dv commented Aug 20, 2017

@Temoto-kun, still didn't try your demo, but since @Hypnosphi managed to run it without problems, I may assume it's related to clean environment. Did you try to delete all the lock files and node_modules and to install them again ?

@Hypnosphi
Copy link
Member

the easiest way to do that is git clean -fdx (removes everything that's not in git)

@TheoryOfNekomata
Copy link

@igor-dv @Hypnosphi I tried:

  1. git clean -fdx
  2. Remove package-lock.json since (1) does not delete it
  3. npm install
  4. npm run storybook

Nope. Still the same error.

@dbrrt
Copy link

dbrrt commented Aug 22, 2017

@Temoto-kun Just ran storybook on your project without any issue (MacOS Sierra 10.12, node 5.3.0 so an old version). Have you access to a Linux machine?

@MattKunze
Copy link

I'm running into the same issue, it seems to happen when I have the storyshots addon installed and use dynamic module loading. Basically it's finding the sample dynamic stories in node_modules and failing when it tries to include them along with my code.

I'm able to work around this by only including the folders I want evaluated in 'config.js':

const req = require.context('../', true, /.*\/src\/*\.stories\.js$/)
function loadStories() {
  req.keys().forEach(filename => req(filename))
}

I haven't had luck getting it to exclude node_modules (it seems like const req = require.context('../', true, /^((?!node_modules).)*\.stories\.js$/) should work, but I get the same error)

@TheoryOfNekomata
Copy link

@dbrrt Sorry, I don't have a Linux machine. Only using macOS 10.12.6 (Node 8.1.4) and Windows 10.

@dbrrt
Copy link

dbrrt commented Aug 30, 2017

@Temoto-kun I'm using almost the same configuration for macOS (10.12.6) and Node 8.2.1 as you, and I was able to run correctly storybook. Which version of storybook are you using ? Have you tried to update @storybook/cli?

@dmmarmol
Copy link
Author

dmmarmol commented Sep 4, 2017

I fixed this issue by looking at some of the webpack.config.js files from examples shared by storybooks. In the project that I'm working on they decided to move to another styleguide generator but I managed to make it work before moving it so in case someone want's to have a look at it, here it's my working webpack.config file:

var path = require('path');

module.exports = {
	module: {
		rules: [
			// Transform all ES6 files to plain old ES5.
			{
				test: /\.(js|jsx)$/,
				exclude: [/bower_components/, /node_modules/, /styles/],
				loader: 'babel-loader',
				include: path.resolve(__dirname, '../../src')
			},
			// Load images.
			{
				test: /\.(gif|jpe?g|png)$/,
				loader: 'url-loader?limit=25000',
				query: {
					limit: 10000,
					name: 'static/media/images/[name].[hash:8].[ext]'
				}
			},
			{
				test: /\.scss$/,
				loaders: ['style-loader', 'css-loader', 'sass-loader', 'resolve-url-loader?sourceMap', 'sass-loader?sourceMap'],
				include: path.resolve(__dirname, '../../')
			},
			{
				test: /\.css$/,
				loader: 'style!css?importLoaders=1'
			},
			// Fonts
			{
				test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
				loader: 'url-loader?limit=10000&mimetype=application/font-woff',
				query: {
					name: 'static/media/files/[name].[hash:8].[ext]'
				}
			},
			{
				test: /\.svg$/,
				use: [
					{
						loader: 'babel-loader',
						query: {
							presets: ['airbnb'],
						},
					},
					{
						loader: 'react-svg-loader',
						query: {
							jsx: true,
						},
					},
				],
			},
		],
	},
	/**
	 * Resolve import paths from global.SRCDIR
	 * @see  http://moduscreate.com/es6-es2015-import-no-relative-path-webpack/
	 */
	resolve: {
		modules: [
			path.resolve(__dirname, '../../src'),
			path.resolve(__dirname, '../../node_modules'),
		],
		extensions: ['.js', '.jsx']
	}
};

@unutoiul
Copy link

Hi Guys,

If i have a repository with shared component across different projects and I do npm install with my private-shared-components library my shared components and story book is inside node_modules...I can't run story book from the parent project I get this:

You may need an appropriate loader to handle this file type.

What's the solution?

Thanks,
Lucas

@dbrrt
Copy link

dbrrt commented Oct 26, 2017

@unutoiul maybe creating a custom webpack file for storybook. It did the job for me.

@dbrrt
Copy link

dbrrt commented May 17, 2018

@badave I don't think that's related to JSX directly, but to any format not handled by webpack, if you want to have webpack loading markdown, then install the proper parser, and restart, same for JSX or SCSS :)

@shashankKeshava
Copy link

@helloncanella @pouyajabbarisani I had set the include point to src/index.js instead of src/ which fixed my issue.

Common Path

/* Location of all Paths used */

const path = require('path');

module.exports = {
    srcPath:path.resolve(__dirname, '../src/'),
    inputPath: path.resolve(__dirname, '../src/index.js'),
    outputPath: path.resolve(__dirname, '../public')
}

Webpack.config.js

'use strict';

const webpack = require('webpack');
const htmlWebpack = require('html-webpack-plugin');

const commonPaths = require('./common-paths');

module.exports = {
    // Entry: First file webpack starts(your dependency graph)
    entry: {
        app: commonPaths.inputPath,
    },
    // Output: How and where to put bundles and format them
    output: {
        filename: 'bundle.js',
        path: commonPaths.outputPath,
        publicPath: '/',
    },
    // Loaders:  How to treat files before adding to dependency graphs
    module: {
        rules: [{
                test: /\.(js|jsx)$/,
                include: [commonPaths.srcPath],
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['es2015', {
                                modules: false
                            }], 'react', 'airbnb'
                        ],
                        plugins: ['transform-runtime'],
                        cacheDirectory: true,
                    },
                },
            },
            {
                test: /\.png$/,
                exclude: /node_modules/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 1000,
                    },
                }, ],
            },
        ],
    },
    // Plugins: Extremely Customizable
    plugins: [
        new webpack.ProgressPlugin(),
        new htmlWebpack({
            template: `${commonPaths.outputPath}/index.html`,
        }),
    ],
};

@nerdyman
Copy link

I was having this issue in any module with JSX in it with @storybook/react@4.0.0-alpha.14. I assumed that there would already be handling for JSX out of the box - but apparently not.

I got it working with the this config:

// webpack.config.js
module.exports = {
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['react'],
                        },
                    },
                ],
            },
        ],
    },
};

@monsooness
Copy link

monsooness commented Jul 29, 2018

Hello, I am having the same problem. I think I have both loaders and I import css in my main jsx file. This is my webpack configurations. Please help!

`const path = require('path');

module.exports = {
  entry: './client/src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'client/dist'),
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['react', 'env'],
          },
        },
      },
      {
        test: [/\.css$/],
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' },
        ],
      },
    ],
  },
  devtool: 'source-map',
};`

@ndelangen
Copy link
Member

@monsooness is that the webpack.config.js in the .storybook folder? Seems like that wouls be the config for your app.

To configure storybook's webpack config you need a webpack.config.js in the .storybook folder.

https://storybook.js.org/configurations/custom-webpack-config/

@dbrrt
Copy link

dbrrt commented Jul 29, 2018

@ndelangen You can have a custom webpack.config.js in your .storybook folder, it's not mandatory, but in most cases you need specific modules/parsers/rules to start your storybook app, then it's in this file you should add these.

dansteren added a commit to dansteren/storybook-tester that referenced this issue Oct 23, 2018
The jsx story was breaking storybook so I removed it. It probably needs
a custom webpack.config.js inside /config/storybook.
See storybookjs/storybook#1493
@tj
Copy link

tj commented Apr 18, 2019

Seems like npm-linked projects aren't supported or something? I get these errors when linking a React project, makes it kind of hard to use private packages. Parcel supports packages with "source": true in the package.json in order to compile those as well, maybe similar could be supported?

@ndelangen
Copy link
Member

@tj I think the issue is that the file's path matches the ignore regex for the babel loader or it doesn't match the include regex.

Can you try to use a custom webpack config that changes those regex's so your files will pass through the babel loader?

@tj
Copy link

tj commented Apr 20, 2019

I'm not familiar with webpack at all, I try hard to avoid it :D. It would be amazing if whatever the defaults are supported npm-linked stuff but I'll try

@Luchanso
Copy link
Member

@ndelangen example repository for reproduce problem:

https://github.com/Luchanso/storybook-typescript-problem

Outputs logs:

Maybe later I'll try to play with webpack.config.js

@AssisrMatheus
Copy link

@Luchanso did you manage to get it to work?

@Luchanso
Copy link
Member

Luchanso commented Sep 6, 2019

@AssisrMatheus I'll take manage it on the weekend

@Luchanso
Copy link
Member

Luchanso commented Sep 13, 2019

@AssisrMatheus, @d-spiridonov, @lucasavila00 I created example repo with problem solution storybook-typescript-problem.

@Lpaydat
Copy link

Lpaydat commented Sep 15, 2019

@Luchanso Your example works! It saves my day, thank you.

@zhaoyao91
Copy link

@Luchanso Your example works! It saves my year, thank you.

@pfmartins4
Copy link

pfmartins4 commented Apr 26, 2020

I'm facing the same problem here

Project Package.json

{
   "dependencies": {
       "@babel/preset-react": "^7.9.4",
      "babel-plugin-root-import": "^6.5.0",
    "material-icons-react": "^1.0.4",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "styled-components": "^5.1.0"
  },
  "scripts": {
    "start": "webpack-dev-server --mode development --open --hot",
    "storybook": "start-storybook"
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.9.5",
    "@storybook/react": "^5.3.18",
    "babel-loader": "^8.1.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  }
}

Project webpack.config.js

module.exports = {
	entry: './src/app',
	output: {
		filename: 'bundle.js'
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				exclude: /node_modules/,
				use: ['babel-loader']
			}
		]
	},
	resolve: {
		extensions: ['*', '.js', '.jsx']
	}
};

.storybook/main.js

module.exports = {
    stories: ['../src/components/**/*.stories.js', '../src/styles/*.stories.js'],
    webpackFinal: (config) => console.dir(config, { depth: null }) || config,
};

Story

import React from 'react';
import { Button } from '@storybook/react/demo';

export default { title: 'Button' };

export const withText = () => <Button>Hello Button</Button>;

export const withEmoji = () => (
    <Button>
        <span role="img" aria-label="so cool">
            😀 😎 👍 💯
    </span>
    </Button>
);

the output from webpackFinal

{ mode: 'development',
  bail: false,
  devtool: '#cheap-module-source-map',
  entry:
   [ '/Users/macbook/repo/node_modules/@storybook/core/dist/server/common/polyfills.js',
     '/Users/macbook/repo/node_modules/@storybook/core/dist/server/preview/globals.js',
     '/Users/macbook/repo/.storybook/generated-entry.js',
     '/Users/macbook/repo/node_modules/webpack-hot-middleware/client.js?reload=true&quiet=true' ],
  output:
   { path:
      '/Users/macbook/repo/node_modules/@storybook/core/dist/public',
     filename: '[name].[hash].bundle.js',
     publicPath: '' },
  plugins:
   [ VirtualModulesPlugin {
       _staticModules:
        { '/Users/macbook/repo/.storybook/generated-entry.js':
           '\n              import { configure } from \'@storybook/react\';\n              module._StorybookPreserveDecorators = true;\n\n              configure([require.context(\'../src/components\', true, /^\\.\\/(?:(?:(?!\\.)(?:(?:(?!(?:|\\/)\\.).)*?)\\/)?(?!\\.)(?=.)[^\\/]*?\\.stories\\.js\\/?)$/),require.context(\'../src/styles\', false, /^\\.\\/(?:(?!\\.)(?=.)[^\\/]*?\\.stories\\.js\\/?)$/)\n              ], module);\n            ' } },
     HtmlWebpackPlugin {
       options:
        { template:
           '/Users/macbook/repo/node_modules/@storybook/core/dist/server/templates/index.ejs',
          templateContent: false,
          templateParameters: [Function: templateParameters],
          filename: 'iframe.html',
          hash: false,
          inject: false,
          scriptLoading: 'blocking',
          compile: true,
          favicon: false,
          minify:
           { collapseWhitespace: true,
             removeComments: true,
             removeRedundantAttributes: true,
             removeScriptTypeAttributes: false,
             removeStyleLinkTypeAttributes: true,
             useShortDoctype: true },
          cache: true,
          showErrors: true,
          chunks: 'all',
          excludeChunks: [],
          chunksSortMode: 'none',
          meta: {},
          base: false,
          title: 'Webpack App',
          xhtml: false,
          alwaysWriteToDisk: true },
       childCompilerHash: undefined,
       assetJson: undefined,
       hash: undefined,
       version: 4 },
     DefinePlugin {
       definitions:
        { 'process.env':
           { NODE_ENV: '"development"', NODE_PATH: '""', PUBLIC_URL: '"."' },
          NODE_ENV: '"development"' } },
     WatchMissingNodeModulesPlugin { nodeModulesPath: '/Users/macbook/repo/node_modules' },
     HotModuleReplacementPlugin {
       options: {},
       multiStep: undefined,
       fullBuildTimeout: 200,
       requestTimeout: 10000 },
     CaseSensitivePathsPlugin {
       options: {},
       logger:
        Console {
          log: [Function: bound consoleCall],
          debug: [Function: bound consoleCall],
          info: [Function: bound consoleCall],
          dirxml: [Function: bound consoleCall],
          warn: [Function: bound consoleCall],
          error: [Function: bound consoleCall],
          dir: [Function: bound consoleCall],
          time: [Function: bound consoleCall],
          timeEnd: [Function: bound consoleCall],
          timeLog: [Function: bound timeLog],
          trace: [Function: bound consoleCall],
          assert: [Function: bound consoleCall],
          clear: [Function: bound consoleCall],
          count: [Function: bound consoleCall],
          countReset: [Function: bound consoleCall],
          group: [Function: bound consoleCall],
          groupCollapsed: [Function: bound consoleCall],
          groupEnd: [Function: bound consoleCall],
          table: [Function: bound consoleCall],
          Console: [Function: Console],
          markTimeline: [Function: markTimeline],
          profile: [Function: profile],
          profileEnd: [Function: profileEnd],
          timeline: [Function: timeline],
          timelineEnd: [Function: timelineEnd],
          timeStamp: [Function: timeStamp],
          context: [Function: context],
          [Symbol(counts)]: Map {},
          [Symbol(kColorMode)]: 'auto' },
       pathCache: {},
       fsOperations: 0,
       primed: false },
     ProgressPlugin {
       profile: false,
       handler: undefined,
       modulesCount: 500,
       showEntries: false,
       showModules: true,
       showActiveModules: true },
     DefinePlugin { definitions: {} },
     NormalModuleReplacementPlugin { resourceRegExp: /core-js/, newResource: [Function] } ],
  module:
   { rules:
      [ { test: /\.(mjs|jsx?)$/,
          use:
           [ { loader: 'babel-loader',
               options:
                { cacheDirectory: '/Users/macbook/repo/node_modules/.cache/storybook',
                  presets:
                   [ [ '/Users/macbook/repo/node_modules/@babel/preset-env/lib/index.js',
                       { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' } ],
                     '/Users/macbook/repo/node_modules/@babel/preset-react/lib/index.js',
                     '/Users/macbook/repo/node_modules/@babel/preset-flow/lib/index.js' ],
                  plugins:
                   [ '/Users/macbook/repo/node_modules/@babel/plugin-proposal-object-rest-spread/lib/index.js',
                     '/Users/macbook/repo/node_modules/@babel/plugin-proposal-class-properties/lib/index.js',
                     '/Users/macbook/repo/node_modules/@babel/plugin-syntax-dynamic-import/lib/index.js',
                     [ '/Users/macbook/repo/node_modules/babel-plugin-emotion/dist/babel-plugin-emotion.cjs.js',
                       { sourceMap: true, autoLabel: true } ],
                     '/Users/macbook/repo/node_modules/babel-plugin-macros/dist/index.js',
                     '/Users/macbook/repo/node_modules/@babel/plugin-transform-react-constant-elements/lib/index.js',
                     '/Users/macbook/repo/node_modules/babel-plugin-add-react-displayname/index.js',
                     [ '/Users/macbook/repo/node_modules/babel-plugin-react-docgen/lib/index.js',
                       { DOC_GEN_COLLECTION_NAME: 'STORYBOOK_REACT_CLASSES' } ] ] } } ],
          include: [ '/Users/macbook/repo' ],
          exclude: [ '/Users/macbook/repo/node_modules' ] },
        { test: /\.md$/,
          use:
           [ { loader: '/Users/macbook/repo/node_modules/raw-loader/dist/cjs.js' } ] },
        { test: /\.css$/,
          sideEffects: true,
          use:
           [ '/Users/macbook/repo/node_modules/style-loader/dist/cjs.js',
             { loader: '/Users/macbook/repo/node_modules/css-loader/dist/cjs.js',
               options: { importLoaders: 1 } },
             { loader:
                '/Users/macbook/repo/node_modules/postcss-loader/src/index.js',
               options:
                { ident: 'postcss', postcss: {}, plugins: [Function: plugins] } } ] },
        { test:
           /\.(svg|ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani|pdf)(\?.*)?$/,
          loader: '/Users/macbook/repo/node_modules/file-loader/dist/cjs.js',
          query: { name: 'static/media/[name].[hash:8].[ext]' } },
        { test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
          loader: '/Users/macbook/repo/node_modules/url-loader/dist/cjs.js',
          query: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } } ] },
  resolve:
   { extensions: [ '.mjs', '.js', '.jsx', '.json' ],
     modules: [ 'node_modules' ],
     alias:
      { 'babel-runtime/core-js/object/assign':
         '/Users/macbook/repo/node_modules/core-js/es/object/assign.js',
        react: '/Users/macbook/repo/node_modules/react',
        'react-dom': '/Users/macbook/repo/node_modules/react-dom' } },
  optimization:
   { splitChunks: { chunks: 'all' },
     runtimeChunk: true,
     minimizer:
      [ TerserPlugin {
          options:
           { test: /\.m?js(\?.*)?$/i,
             chunkFilter: [Function: chunkFilter],
             warningsFilter: [Function: warningsFilter],
             extractComments: true,
             sourceMap: true,
             cache: true,
             cacheKeys: [Function: cacheKeys],
             parallel: true,
             include: undefined,
             exclude: undefined,
             minify: undefined,
             terserOptions: { mangle: false, keep_fnames: true } } } ] },
  performance: { hints: false } }

An finally i'm not sure why it's not indenting

thanks

@ndelangen
Copy link
Member

Please paste the complete terminal errors here @pfmartins4 otherwise I can't know what's wrong.

@kaleem-elahi
Copy link

kaleem-elahi commented Apr 14, 2021

i am getting same isssue looks like it is something rrelated to SCSS loader of webpack

image

@flutterq
Copy link

[Solved] Failed to compile : ./node_modules/@react-leaflet/core/esm/path.js 10:41 Module parse failed: Unexpected token (10:41)

@isc30
Copy link

isc30 commented Oct 30, 2021

for people facing this issue in newer versions of storybook:

.storybook/main.js

module.exports = {
  ...
  webpackFinal: (config) => {
    config.module.rules.push({
      test: /\.tsx?$/,
      exclude: /node_modules/,
      use: [
        {
          loader: require.resolve('babel-loader'),
          options: {
            presets: [
              require('@babel/preset-typescript').default,
              [require('@babel/preset-react').default, { runtime: 'automatic' }],
              require('@babel/preset-env').default,
            ],
          },
        },
      ],
    })

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

    config.module.rules.push({
      test: /\.mjs$/,
      include: /node_modules/,
      type: 'javascript/auto',
    })

    config.resolve.extensions.push('.mjs')

    return config
  },
}

@dibenso
Copy link

dibenso commented Nov 4, 2021

@isc30 thanks for this 👍
Can confirm this works for my case:
Lerna create-react-app monorepo using Typescript.
Now all my stories (other than the example introduction that comes shipped with Storybook) show up!

@sayo96
Copy link

sayo96 commented Dec 9, 2022

I'm still running into this. @isc30 Your fix did not work for me 😢

@mohit-gyaan
Copy link

for people facing this issue in newer versions of storybook:

.storybook/main.js

module.exports = {
  ...
  webpackFinal: (config) => {
    config.module.rules.push({
      test: /\.tsx?$/,
      exclude: /node_modules/,
      use: [
        {
          loader: require.resolve('babel-loader'),
          options: {
            presets: [
              require('@babel/preset-typescript').default,
              [require('@babel/preset-react').default, { runtime: 'automatic' }],
              require('@babel/preset-env').default,
            ],
          },
        },
      ],
    })

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

    config.module.rules.push({
      test: /\.mjs$/,
      include: /node_modules/,
      type: 'javascript/auto',
    })

    config.resolve.extensions.push('.mjs')

    return config
  },
}

@isc30 Thanks for this
This works in my case

@Kucerenko171
Copy link

Did it. But it doesn't work

@mmo0307
Copy link

mmo0307 commented Feb 3, 2024

@Kucerenko171 Try to connect this loader
{
test: /.s[ac]ss$/i,
use: [
// Creates style nodes from JS strings
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
}

@Kucerenko171
Copy link

@mmo0307 it looks working. Thank you

@mmo0307
Copy link

mmo0307 commented Feb 3, 2024

@Kucerenko171 Do you use latest version of storybook?

@acbonnyac
Copy link

I upgraded Storybook from v7 to v8 and started getting failures about import syntax not recognized, which is an indicator that babel is not being used to load files properly. I only needed this portion to fix my Storybook to use babel-loader properly (thanks @isc30 for the original code!):

    webpackFinal: (webpackConfig) => {
        webpackConfig.module?.rules?.push({
            test: /\.tsx?$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: require.resolve('babel-loader'),
                },
            ],
        });

        webpackConfig.resolve?.extensions?.push('.ts', '.tsx');

        return webpackConfig;
    },

Still, would be nice to know why we have to do this though. Why is Storybook v8 breaking this when Storybook v7 worked before?

@shivam-cedcoss
Copy link

shivam-cedcoss commented May 8, 2024

All the person who are facing this issue can install this extension in storybook 8

npm i @storybook/addon-webpack5-compiler-swc

and add it to your main.js or main.ts file

Example :
const config = {
stories: ["../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
addons: [
(here rest of your addons)
"@storybook/addon-webpack5-compiler-swc",
],
};
export default config;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests