react-styleguidist icon indicating copy to clipboard operation
react-styleguidist copied to clipboard

Not correctly loading components that use webpack aliases

Open joepio opened this issue 9 years ago • 11 comments

First of all: thank you all for your hard work. I love this project.

However, since a couple of weeks, Styleguidist doesn't build correctly. It seems to struggle with parsing some specific JSON files. When I tried to found out which components might cause that, I noticed that this error message only appears with components that import other components using Webpack aliases. When I switched to relative import statements, the problem disappeared. These aliases don't seem to cause any issues unrelated to Styleguidist.

Here's an example of such a component with aliases:

import React, { PropTypes } from 'react';
// Using a relative path instead of an alias fixes the problem
// import Button from '../../Components/Button';
import { Button } from 'components';
...

The browser windows only shows Cannot GET /. A couple of errors similar to the one below appear in the console, all happening in .json files in /node_modules/entities/maps/xml.json.

ERROR in ./~/entities/maps/xml.json
Module parse failed: /Users/joep/Dev/aod_demo/node_modules/entities/maps/xml.json Unexpected token (1:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:6)
    at Parser.pp$4.raise (/Users/joep/Dev/aod_demo/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp.unexpected
...

A similar issue (with the same errors in console) was discussed here. The solution seemed to be adding JSON-loader, but that did not work for me.

/styleguide.config.js

const path = require('path');
const webpackCommonConfig = require('./webpack/common.config.js');

module.exports = {
  title: 'React Style Guide',
  components: './app/components/**/*.jsx',
  serverPort: 5000,
  showCode: false,
  updateWebpackConfig: ((webpackConfig) => {
    // I suspect that this alias resolver may be the cause of the error.
    Object.assign(webpackConfig.resolve.alias, webpackCommonConfig.resolve.alias);
    webpackConfig.entry.push(path.join(__dirname, 'app/components/shared/styleguide.scss'));
    webpackConfig.entry.unshift(path.join(__dirname, 'app/components/shared/init.scss'));
    webpackConfig.module.loaders.push({
      test: /\.jsx?$/,
      loader: 'babel',
      include: path.join(__dirname, 'app'),
      exclude: /node_modules/,
    }, {
      test: /\.scss$/,
      include: path.join(__dirname, 'app'),
      loader: 'style!css-loader!postcss-loader!sass-loader',
    }, {
      // I tried including this json-loader, but that does not seem to help. Perhaps it's overkill, since it is already included in common.config.js
      test: /\.json$/,
      include: '**/*',
      loader: 'json-loader',
    });
    return webpackConfig;
  }),
};

And here's my /webpack/common.config.js:

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HappyPack = require('happypack');

const TARGET = process.env.npm_lifecycle_event;
process.env.BABEL_ENV = TARGET;
const common = {
  output: {
    path: `${__dirname}/../dist/`,
    filename: 'bundle.js',
  },

  resolve: {
    modulesDirectories: ['./node_modules'],
    extensions: ['', '.js', '.jsx', '.ts'],
    alias: {
      components: path.resolve('app/components'),
      containers: path.resolve('app/containers'),
      helpers: path.resolve('app/helpers'),
      models: path.resolve('app/models'),
      react: path.resolve('./node_modules/react'),
      state: path.resolve('app/state'),
    },
  },

  module: {
    loaders: [
      {
        test: /(\.jsx\.js)?$/,
        loaders: ['happypack/loader?id=babel'],
        exclude: /node_modules/,
        include: /app/,
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
      },
      {
        test: /\.png$/,
        loader: 'file?name=[name].[ext]',
      }, {
        test: /\.jpg$/,
        loader: 'file?name=[name].[ext]',
      },
    ],
  },

  plugins: [
    new webpack.ProvidePlugin({
      fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    }),
    new webpack.DefinePlugin({
      'process.env.ELASTICSEARCH_URL': JSON.stringify(process.env.ELASTICSEARCH_URL),
      'process.env': {
        NODE_ENV: process.env.NODE_ENV === 'development' ? '"development"' : '"production"',
      },
      __DEVELOPMENT__: process.env.NODE_ENV === 'development',
      __PRODUCTION__: process.env.NODE_ENV === 'production',
      __CLIENT__: true,
    }),
    new HappyPack({
      id: 'babel',
      threads: 4,
      loaders: ['babel-loader?cacheDirectory'],
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    // new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en|nl/),
  ],
  postcss: [autoprefixer({ browsers: ['last 2 versions'] })],
};

module.exports = common;

I'm running webpack 1.14.0 and node 7.3.0

Thank you for your time!

joepio avatar Jan 10 '17 19:01 joepio

The problem with JSON might be because of your includes mask. Since we already have a json-loader it will just try to apply it twice for certain files. That’s why require include option for all user loaders (it‘s not the case for upcoming 5.0.0).

But I’m not sure what‘s wrong with aliases. The react alias looks suspicious but I don‘t think that it‘s a problem.

I’d suggest you to try beta of Styleguidist 5.0.0 (npm i [email protected]). Docs: https://github.com/styleguidist/react-styleguidist/tree/next/docs (especially Getting Started). I’ll write a changelong in the next few days. There are lots of changes in our Webpack config that should reduce number of issues with user configuration.

sapegin avatar Jan 10 '17 20:01 sapegin

Thanks for the quick reply, @sapegin!

The beta seems to work better! No more JSON import issues. And I think I've found the issue regarding the aliases. Using aliases somehow called a defective function in some dependency not related to Styleguidist. When I fixed that issue, the components started working again. I still find it odd that my normal build worked fine, since that also relied on that same defective dependency and aliases.

When I tried to re-use my project’s Webpack config file, I got error messages from all components that HappyPack for Babel cannot be found:

Minimal styleguide.config:

module.exports = {
  components: './app/components/**/*.jsx',
  webpackConfigFile: './webpack/common.config.js',
};

Errors:

Failed to compile.

Error in ./app/components/Button/index.jsx
Module build failed: AssertionError: HappyPack: plugin for the loader 'babel' could not be found! Did you forget to add it to the plugin list?
 @ ./~/react-styleguidist/loaders/styleguide-loader.js!./~/react-styleguidist/lib/index.js 5:10-77

However, the Happypack babel plugin is present in /webpack/common.config.js as you can see in my first post.

So then I tried including a custom webpackConfig based on my common.config.js:

/styleguide.config.js

const path = require('path');
const HappyPack = require('happypack');
const autoprefixer = require('autoprefixer');

module.exports = {
  serverPort: 5000,
  sections: [
    {
      name: 'Card Components',
      content: './app/components/Card/Card.md',
      components: './app/components/Card/*.jsx',
    },
  ],
  components: './app/components/**/*.jsx',
  showCode: false,
  webpackConfig: {
    resolve: {
      modulesDirectories: ['./node_modules'],
      extensions: ['', '.js', '.jsx', '.ts'],
      alias: {
        components: path.resolve('app/components'),
        containers: path.resolve('app/containers'),
        helpers: path.resolve('app/helpers'),
        models: path.resolve('app/models'),
        react: path.resolve('./node_modules/react'),
        state: path.resolve('app/state'),
      },
    },
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loader: 'babel',
          include: path.join(__dirname, 'app'),
          exclude: /node_modules/,
        }, {
          test: /\.scss$/,
          include: path.join(__dirname, 'app'),
          loader: 'style!css-loader!postcss-loader!sass-loader',
        },
      ],
      plugins: [
        new HappyPack({
          id: 'babel',
          threads: 4,
          loaders: ['babel-loader?cacheDirectory'],
        }),
      ],
      postcss: [autoprefixer({ browsers: ['last 2 versions'] })],
    },
    entry: [
      path.join(__dirname, 'app/components/shared/styleguide.scss'),
      path.join(__dirname, 'app/components/shared/init.scss'),
    ],
  },
};

This works exactly as it should :).

Thanks for the help! I think this issue can be closed.

joepio avatar Jan 11 '17 11:01 joepio

Thanks you very much for feedback!

When I tried to re-use my project’s Webpack config file, I got error messages from all components that HappyPack for Babel cannot be found

That’s because we ignore plugins when you use webpackConfigFile (but not webpackConfig) to prevent problems with duplicated plugins (like HMR). I’m going to try to implement smarter merging and see how it works.

sapegin avatar Jan 11 '17 13:01 sapegin

Great! Let me know if I can test something.

joepio avatar Jan 11 '17 14:01 joepio

Hi @joepsz, we have a new beta: https://github.com/styleguidist/react-styleguidist/releases/tag/5.0.0%40beta.9 and it does plugins merging.

sapegin avatar Jan 25 '17 19:01 sapegin

Hi @sapegin,

Thanks for the heads-up. I tried plugin merging again, but unfortunately, it doesn't seem to be working correctly. I get this error for basically all jsx files:

Failed to compile.

Error in ./app/components/ArgumentShow/index.jsx
Module parse failed: /Users/joep/Dev/aod_demo/app/components/ArgumentShow/index.jsx Unexpected token (32:2)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (32:2)
 @ ./~/react-styleguidist/loaders/styleguide-loader.js!./~/react-styleguidist/lib/index.js 36:22-95

When I just use my old config, it works fine!

joepio avatar Feb 09 '17 13:02 joepio

@joepsz Could you show what config are you trying to use now and it doesn’t work?

sapegin avatar Feb 09 '17 13:02 sapegin

So this one works:

const common = require('./webpack/common.config');

module.exports = {
  webpackConfigFile: './webpack/common.config.js',
  serverPort: 5000,
  sections: [
    {
      name: 'Card Components',
      content: './app/components/Card/Card.md',
      components: './app/components/Card/*.jsx',
    },
  ],
  components: './app/components/**/index.jsx',
  showCode: false,
  webpackConfig: {
    resolve: common.resolve,
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loader: 'babel',
          include: path.join(__dirname, 'app'),
          exclude: /node_modules/,
        }, {
          test: /\.scss$/,
          include: path.join(__dirname, 'app'),
          loader: 'style!css-loader!postcss-loader!sass-loader',
        }, {
          test: /\.md$/,
          loader: 'raw-loader',
        },
      ],
      plugins: [
        new HappyPack({
          id: 'babel',
          threads: 4,
          loaders: ['babel-loader?cacheDirectory'],
        }),
      ],
      postcss: [autoprefixer({ browsers: ['last 2 versions'] })],
    },
    entry: [
      path.join(__dirname, 'app/components/shared/styleguide.scss'),
      path.join(__dirname, 'app/components/shared/init.scss'),
    ],
  },
};

And this throws the Module parse failed errors:

module.exports = {
  webpackConfigFile: './webpack/common.config.js',
  serverPort: 5000,
  sections: [
    {
      name: 'Card Components',
      content: './app/components/Card/Card.md',
      components: './app/components/Card/*.jsx',
    },
  ],
  components: './app/components/**/index.jsx',
  showCode: false,
};

And here's my common.config.js:

const path = require('path');

const autoprefixer = require('autoprefixer');
const webpack = require('webpack');

const TARGET = process.env.npm_lifecycle_event;
process.env.BABEL_ENV = TARGET;
const common = {
  output: {
    path: `${__dirname}/../dist/`,
    filename: 'bundle.js',
  },

  resolve: {
    modulesDirectories: ['./node_modules'],
    extensions: ['', '.js', '.jsx', '.ts'],
    alias: {
      components: path.resolve('app/components'),
      containers: path.resolve('app/containers'),
      helpers: path.resolve('app/helpers'),
      models: path.resolve('app/models'),
      state: path.resolve('app/state'),
      static: path.resolve('static'),
    },
  },

  module: {
    loaders: [
      {
        test: /\.json$/,
        loader: 'json-loader',
      },
      {
        test: /\.png$/,
        loader: 'file?name=[name].[ext]',
      }, {
        test: /\.jpg$/,
        loader: 'file?name=[name].[ext]',
      }, {
        test: /\.md$/,
        loader: 'raw-loader',
      },
    ],
  },

  plugins: [
    new webpack.ProvidePlugin({
      fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    }),
    new webpack.DefinePlugin({
      'process.env.ELASTICSEARCH_URL': JSON.stringify(process.env.ELASTICSEARCH_URL),
      'process.env': {
        NODE_ENV: process.env.NODE_ENV === 'development' ? '"development"' : '"production"',
        ARGU_API_URL: JSON.stringify(process.env.ARGU_API_URL),
      },
      __DEVELOPMENT__: process.env.NODE_ENV === 'development',
      __PRODUCTION__: process.env.NODE_ENV === 'production',
      __CLIENT__: true,
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  postcss: [autoprefixer({ browsers: ['last 2 versions'] })],
};

module.exports = common;

joepio avatar Feb 09 '17 16:02 joepio

I think if you make [--- path.resolve('app/components') ---] path.resolve(__dirname, 'app/components')

it will work bcoz it work for me

moelzanaty3 avatar Mar 05 '17 12:03 moelzanaty3

Sorry, I didn’t have time to check it. Do you still have this issue? Could you please try in the latest beta? It has some changes in webpack configuration.

sapegin avatar Mar 11 '17 12:03 sapegin

Closing this for now. Feel free to reopen if you still have this issue.

5.0.0 is out by the way ;-)

sapegin avatar Mar 31 '17 09:03 sapegin