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

Error: exports is not defined #3346

Closed
Olian04 opened this issue Apr 3, 2018 · 83 comments
Closed

Error: exports is not defined #3346

Olian04 opened this issue Apr 3, 2018 · 83 comments

Comments

@Olian04
Copy link

Olian04 commented Apr 3, 2018

I'm trying to use storybook for the first time, so I decided to follow the guides.
I can get it working with the examples, but as soon as i pull in my own components i get exports is not defined.
It doesn't matter if I use the "Quick Start Guide" or the "Slow Start Guide (React)" I always get the same unhelpful error.

exports is not defined

ReferenceError: exports is not defined
at Object. (http://localhost:6006/static/preview.bundle.js:43176:23)
at webpack_require (http://localhost:6006/static/preview.bundle.js:679:30)
at fn (http://localhost:6006/static/preview.bundle.js:89:20)
at Object. (http://localhost:6006/static/preview.bundle.js:43132:76)
at Object. (http://localhost:6006/static/preview.bundle.js:43142:30)
at webpack_require (http://localhost:6006/static/preview.bundle.js:679:30)
at fn (http://localhost:6006/static/preview.bundle.js:89:20)
at loadStories (http://localhost:6006/static/preview.bundle.js:40160:3)
at ConfigApi._renderMain (http://localhost:6006/static/preview.bundle.js:41134:20)
at render (http://localhost:6006/static/preview.bundle.js:41092:17)
at ConfigApi.configure (http://localhost:6006/static/preview.bundle.js:41117:9)
at Object. (http://localhost:6006/static/preview.bundle.js:40164:68)
at Object.defineProperty.value (http://localhost:6006/static/preview.bundle.js:40165:30)
at webpack_require (http://localhost:6006/static/preview.bundle.js:679:30)
at fn (http://localhost:6006/static/preview.bundle.js:89:20)
at Object.window.STORYBOOK_REACT_CLASSES (http://localhost:6006/static/preview.bundle.js:38867:18)
at webpack_require (http://localhost:6006/static/preview.bundle.js:679:30)
at http://localhost:6006/static/preview.bundle.js:725:39
at http://localhost:6006/static/preview.bundle.js:728:10

That error doesn't really help much, and when I look up the error I end up at some issues from last year all saying that this problem has been patched out...
I know that it's probably my component that is exported in some way that storybook doesn't like. But since all I'm getting is exports is not defined (along with some mess of a stacktrace) its kind of hard to debug.

I'm using typescript and I'm compiling it with just plain old tsc.

//tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "outDir": "./dist",
    "esModuleInterop": true
  },
  "include": [
    "./src/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

And then importing the compiled js into storybooks.

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

import { MatrixEffect } from '../dist/index';

storiesOf('MatrixEffect', module)
  .add('100x100', () => 
    <MatrixEffect height={100} width={100} />
  );

Version

  • @storybook/react 3.4.0
  • @storybook/addon-actions 3.4.0
  • babel-core 6.26.0
  • react 16.3.0

What am I missing?
(if there's a way to just import the ts straight away then that would preferable. But since I haven't found any official docs for it, this is what I've got so far)

@Olian04
Copy link
Author

Olian04 commented Apr 3, 2018

I'm getting export 'MatrixEffect' was not found in '../dist/index' in the terminal. But I can import the module in just a plain node runtime (can't use it ofc, but at least i know it can be imported).

@danielduan
Copy link
Member

this might help since we don't have official docs yet: #3270

@stale stale bot added the inactive label Apr 25, 2018
@Olian04
Copy link
Author

Olian04 commented Apr 25, 2018

This is still not working...

@stale stale bot removed the inactive label Apr 25, 2018
@stale stale bot added the inactive label May 16, 2018
@robertmassaioli
Copy link

I just ran into an issue with the same error message in a storybook after turning on yarn workspaces in a lerna project. I suspect that this is caused by package loading issues. Investigating further.

@stale stale bot removed the inactive label May 19, 2018
@stale stale bot added the inactive label Jun 9, 2018
@minhducsun2002
Copy link

Sounds like I have the identical issue.

@stale stale bot removed the inactive label Jun 10, 2018
@igor-dv
Copy link
Member

igor-dv commented Jun 11, 2018

If I understand the problem right, there is an issue with resolving .ts files from the .js? (Though, I don't understand why you are importing your component from dist)

Maybe you should add .ts/.tsx to the resolve.extensions in your extended storybook webpack.config?

@minhducsun2002
Copy link

@igor-dv No, I use JS. Anyway, changing variable identifier (variable to Variable) works, somehow.

@bencmbrook
Copy link

bencmbrook commented Jun 23, 2018

I'm getting this error without using TypeScript, just vanilla JS

@aneesa-saleh
Copy link

I removed the babel loader from webpack.config.js in the .storybook folder and it works fine now. I don't use Typescript though.

@stale stale bot added the inactive label Jul 27, 2018
@ryanflorence
Copy link

ryanflorence commented Aug 25, 2018

I'm running into this, in the browser I get exports is not defined but in the terminal I get `"export 'default' (imported as '[ComponentName]') was not found in '@[namespace]/[package-name]'"

  • Using lerna
  • Storybook 3.4.7
  • Everything is fine for my components with no internal dependencies
  • If I try to import a module with a dependency on another package in project/packages the error shows up
  • I am running my build scripts, so it's trying to pull in a common-js version of the package.

If I change the internal dependency's package.json main config to the non-built source everything works

So there's something wrong with storybook's webpack config and importing cjs into es module code, or something ...

My fix

So I realized I accidentally deleted my package.json "module" field that pointed to the ES module version of my builds, adding that back in makes everything work again. Still seems like storybook should be able to pull the cjs version, but my problem is solved 🤷🏽‍♂️

@stale stale bot removed the inactive label Aug 25, 2018
@tony
Copy link

tony commented Sep 3, 2018

This is still happening for me in v4.0.0-alpha.20 with babel 7.0.0

@kevinSuttle
Copy link
Contributor

Same here @tony. I'm using Flow, though.

@VrajSolanki
Copy link

@ryanflorence I have the exact same lerna setup and the exports issue for storybook.
I have a package which exposes the built version of the UI-Elements.
Apologies but could you provide more details when you say, "module" field that pointed to the ES module version of my builds, adding that back in makes everything work again.

@pixeleate
Copy link

pixeleate commented Sep 22, 2018

this issue can be fixed by adding the correct plugin in the .babelrc file, since the tsconfig file is configured to generate commonjs compatible modules, we need to use the proper plugin

{
	"env": {
		"test": {
			"plugins": ["instanbul"]
		}
	},
	"plugins": ["@babel/plugin-syntax-dynamic-import", "@babel/plugin-transform-modules-commonjs"]
}

This is what I have in my .babelrc file and everything is working fine, I have my tsconfig file with exactly the same options and values.

"@babel/core" "^7.1.0"
"@storybook/react" ^4.0.0-alpha.2"
"react" "^16.4.0"

Note: This solution works for another kind of modules https://babeljs.io/docs/en/next/plugins#modules

@psychobolt
Copy link

psychobolt commented Sep 28, 2018

For me the issue is caused with the recent changes to include babel-loader in 4.0.0.alpha. The default server webpack config could include your commonjs compiles (packages, workspaces): https://github.com/storybooks/storybook/blob/b2b73596f9dd97b4ba8c03340bd36f868e836772/lib/core/src/server/config/webpack.config.dev.js#L78
https://github.com/storybooks/storybook/blob/b2b73596f9dd97b4ba8c03340bd36f868e836772/lib/core/src/server/config/utils.js#L3

For me, a fix is to override the default plugin declare with a custom webpack.dev.js:

https://github.com/psychobolt/react-rollup-boilerplate/blob/d9cb9179cb7c00baab486646c504110bf7e2f50a/.storybook/webpack.config.js#L7

// exclude 'babel-loader' so we can override it later
...defaultConfig.module.rules.filter(rule => !(
    (rule.use && rule.use.length && rule.use.find(({ loader }) => loader === 'babel-loader'))
)),

https://github.com/psychobolt/react-rollup-boilerplate/blob/d9cb9179cb7c00baab486646c504110bf7e2f50a/.storybook/webpack.config.js#L11

{
  test: /\.jsx?$/,
  include: require('path').resolve('./'),
  exclude: /(node_modules|dist)/, // exclude any commonjs files
  loader: 'babel-loader',
},

Omitting include also fixes the issue and has no side effects for me.

@storybookjs storybookjs deleted a comment from stale bot Oct 13, 2018
@storybookjs storybookjs deleted a comment from stale bot Oct 13, 2018
@storybookjs storybookjs deleted a comment from stale bot Oct 13, 2018
@storybookjs storybookjs deleted a comment from stale bot Oct 13, 2018
@busticated
Copy link

yarn workspaces will hoist all dependencies to the root, this will solve tons of issues.

assuming you use yarn 😉

make a change to storybook to support excluding MULTIPLE node_modules folders by default

is that the root cause? applying the change locally doesn't seem to fix my issue.

i'm getting the following in my browser's console:

TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

...which is a bit different i guess..? yet another error that you see all the time but always has a different solution 🤦‍♂ /me frowns in babel and webpack's general direction 😬

I'm pretty terrified of rolling that change out in a minor release, and so is @shilman. We've decided it's better to hold that until 6.0.

oh yeah i hear you - none of this stuff is ever easy. thank you very much for al the work you do here and elsewhere - storybook (even v3) is an amazingly helpful tool 🙏👏👏👏👍

@i-like-robots
Copy link

i-like-robots commented Nov 15, 2019

TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

This is most likely caused by Webpack wrapping a CommonJS module with its ESM wrapper. Webpack will use an ESM wrapper if it sees any usage of import in the module. It's usually caused by either:

  1. Mixing and matching ESM and CJS in your source code
  2. Babel injecting ESM helpers into a CJS module

To avoid the second case you'll need to set Babel's sourceType to "unambiguous" to force it to check the module type first.

https://github.com/i-like-robots/broken-webpack-bundle-test-case


Update: My original comment is hidden above but this is the base configuration we have been using to resolve these issues across multiple monorepo projects:

const excludePaths = [/node_modules/, /dist/]

module.exports = ({ config }) => {
  // Use real file paths for symlinked dependencies do avoid including them multiple times
  config.resolve.symlinks = true

  // HACK: extend existing JS rule to ensure all dependencies are correctly ignored
  // https://github.com/storybooks/storybook/issues/3346#issuecomment-459439438
  const jsRule = config.module.rules.find((rule) => rule.test.test('.jsx'))
  jsRule.exclude = excludePaths

  // HACK: Instruct Babel to check module type before injecting Core JS polyfills
  // https://github.com/i-like-robots/broken-webpack-bundle-test-case
  const babelConfig = jsRule.use.find(({ loader }) => loader === 'babel-loader')
  babelConfig.options.sourceType = 'unambiguous'

  // HACK: Ensure we only bundle one instance of React
  config.resolve.alias.react = require.resolve('react')

  return config
}

@ndelangen
Copy link
Member

@i-like-robots what's the downside of using sourceType = 'unambiguous'?

@ndelangen
Copy link
Member

Thanks for posting the workaround!

@ndelangen
Copy link
Member

ndelangen commented Nov 15, 2019

I'm going to use this to improve monorepo support: #8822

(6.0.0 feature)

@ndelangen ndelangen added this to the 6.0.0 milestone Nov 15, 2019
@qrosmeli
Copy link

Maybe unrelated, but I was having this exports is not defined issue because of my custom babel.config.js, reading https://storybook.js.org/docs/configurations/custom-babel-config/ solved my particular problem.

@isotopeee
Copy link

@qrosmeli Thanks for the tip. You saved my day! 🚀

@shilman
Copy link
Member

shilman commented Jan 21, 2020

Huzzah!! I just released https://github.com/storybookjs/storybook/releases/tag/v6.0.0-alpha.0 containing PR #8822 that references this issue. Upgrade today to try it out!

You can find this prerelease on the @next NPM tag.

Closing this issue. Please re-open if you think there's still more to do.

@ashvin777
Copy link

ashvin777 commented Apr 15, 2020

[UPDATED] - We have to exclude node_modules from this rule otherwise it will break the build

I have resolved it by adding this rule in storybook main.js file

let rules = [{
  test: /\.(js|mjs|jsx|ts|tsx)$/,
  include: /dist/, //Include dist folder as well to parse using babel loader in order to resolve exports not defined error
  exclude: /node_modules/,
  loader: 'babel-loader',
  options: {
    presets: [
      ["@babel/preset-env", {
        modules: "commonjs"
      }]
    ]
  }
}]

Along with this, you may also need to disable the eslint validations for your dist folder, so for that, you can use below script

  webpackFinal: config => {

    //Find eslint loader rule from webpack config
    let eslintRule = config.module.rules.find(rule => {
      if (rule && rule.use) {
        return rule.use.some(use => use.loader.match('eslint-loader'))
      }
    });

    //Exclude validations of dist folder contents
    eslintRule.exclude = /dist/;

    return {
      ...config,
      module: {
        rules: [
          ...rules,
          eslintRule,
          ...config.module.rules
        ]
      }
    }
  }

@aperkaz
Copy link

aperkaz commented Apr 17, 2020

Thanks @ashvin777, works like a charm 😉

@ashvin777
Copy link

Hey @aperkaz, I have updated the rule to exclude node_modules, I found that storybook was launching properly in dev mode however breaking in production mode because of this change. So I had to exclude node_modules in order to fix. You can take the latest from my updated comment above.

@7michele7
Copy link

I had the exact same issue, and for me the solution was switching from using transform-es2015-modules-commonjs to @babel/plugin-transform-modules-commonjs on babel.config.js.

before

module.exports = {
    presets: [['@babel/preset-env', { modules: false }], '@babel/preset-react'],
    plugins: [
        'transform-es2015-modules-commonjs',
        '@babel/plugin-proposal-class-properties'
    ]
};

after

module.exports = {
    presets: [['@babel/preset-env', { modules: false }], '@babel/preset-react'],
    plugins: [
        '@babel/plugin-transform-modules-commonjs',
        '@babel/plugin-proposal-class-properties'
    ]
};

@bertho-zero
Copy link
Contributor

bertho-zero commented May 12, 2020

TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

I spent the day on this issue, I already had the sourceType: 'unambigous'.

For my part, it was not linked to a node_modules folder to ignore since it is a relative file right next to it.

A workaround that works for me is to force the option modules: 'cjs' for the @babel/preset-env.

I also have this problem with @storybook/react@next, the final solution for me was to manually add the babel plugin @babel/plugin-transform-modules-commonjs, while with the debug: true option on the @babel/preset-env I see that it is already used... I don't understand but it works.

EDIT: This is not a solution because it loses the benefits of ESM modules with webpack. I need to force transform to cjs only for the storybook builds.

🎉 My .storybook/.babelrc: 🎉

{
  "extends": "../.babelrc",
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"
  ]
}

@tresabhi
Copy link

tresabhi commented Aug 2, 2022

Got this to work again with a simple fix:

Remove "module" from tsconfig.json

{
  "module": "commonjs",
}

@pietrofxq
Copy link

I am having the same issue using @storybook/vite-builder. and

{ "type": "module" }

in package.json. Storybook version 6.5.10

@ktorlakonda-eightfold
Copy link

TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

I spent the day on this issue, I already had the sourceType: 'unambigous'.

For my part, it was not linked to a node_modules folder to ignore since it is a relative file right next to it.

A workaround that works for me is to force the option modules: 'cjs' for the @babel/preset-env.

I also have this problem with @storybook/react@next, the final solution for me was to manually add the babel plugin @babel/plugin-transform-modules-commonjs, while with the debug: true option on the @babel/preset-env I see that it is already used... I don't understand but it works.

EDIT: This is not a solution because it loses the benefits of ESM modules with webpack. I need to force transform to cjs only for the storybook builds.

🎉 My .storybook/.babelrc: 🎉

{
  "extends": "../.babelrc",
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"
  ]
}

thank you. this worked

@alonrbar
Copy link

If anyone is still encountering this, here's what worked for me:

Perhaps because my Babel config is named babel.config.js instead of .babelrc, it seems like Storybook did not identify it.
I had to configure Storybook to explicitly read my existing Babel config (https://storybook.js.org/docs/react/configure/babel#custom-configuration), so my main.js now looks like this:

const config = {
    stories: [
        "../stories/**/*.stories.tsx",
    ],
    addons: [
        "@storybook/addon-essentials",
    ],
    framework: "@storybook/react",
    core: {
        builder: "@storybook/builder-webpack5"
    },
    babel: async (options) => {
        // Ignoring the default Storybook options and loading our own:
        const opt = require('../babel.config');
        
        // I'm manually adding "@babel/preset-env" here since my personal setup doesn't 
       // specify it in the main Babel config file. You probably won't need this part.
        opt.presets.unshift(
            [
                "@babel/preset-env",
                {
                    "targets": {
                        "chrome": "108",
                    }
                }
            ]
        )
        return opt;
    },
}
export default config;

I also had to modify the React imports of the example from import React from 'react' to import * as React from 'react' but I guess it depends on your specific setup.

@cdaringe
Copy link

cdaringe commented Nov 5, 2023

Some entity in the compile toolchain is generating code that looks like this:

exports.ArrowSvg = void 0; // exports is not defined here
var react_1 = require("react");
var ArrowSvg = function (_a) { /* SNIP */ }
exports.ArrowSvg = ArrowSvg;

This is still an issue using all @storybook/* packages with TS.

Versions:

$ cat package.json | grep storybook:

    "@storybook/addon-essentials": "^7.5.2",
    "@storybook/addon-interactions": "^7.5.2",
    "@storybook/addon-links": "^7.5.2",
    "@storybook/blocks": "^7.5.2",
    "@storybook/nextjs": "^7.5.2",
    "@storybook/react": "^7.5.2",
    "@storybook/testing-library": "0.2.2",
    "eslint-plugin-storybook": "^0.6.15",
    "storybook": "^7.5.2",
import type { StorybookConfig } from "@storybook/nextjs";
import assert from "assert";
import TsconfigPathsPlugin from "tsconfig-paths-webpack-plugin";

const config: StorybookConfig = {
  stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
  ],
  framework: {
    name: "@storybook/nextjs",
    options: {},
  },
  docs: {
    autodocs: "tag",
  },
  webpackFinal: async (config) => {
    assert(config.resolve);
    config.resolve.plugins = [new TsconfigPathsPlugin()];
    return config;
  },
};
export default config;

iva2k added a commit to iva2k/total-app that referenced this issue Nov 30, 2024
* @rollup/plugin-commonjs was added before to fix cjs files build
* remove @rollup/plugin-commonjs removed to fix `storybook build`
* see storybookjs/storybook#3346 (comment)
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