Andrzej
Andrzej

Reputation: 571

Configure Webpack 4 with aliases, Babel 7 to build React components library

I'm trying to create two React projects:

I would like to achieve a folders structure like:

There are configuration files in example directory (simplest React + webpack config without HMR and other stuff):

webpack.config.js

const HtmlWebPackPlugin = require("html-webpack-plugin");
const aliases = require('./aliases.js');

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader"
          }
        ]
      }
    ]
  },
  resolve: {
    alias: aliases
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html"
    })
  ]
};

aliases.js

var path = require('path');
module.exports = {
  'webpack-alias-react': path.resolve(__dirname, '../src')
};

babel.rc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

VSCode alias config is in jsconfig.json file.

And there is my problem. When ./src/SimpleComponent contains code like that:

const SimpleComponent = () => {
  return 'string';
};

Running npm run build command builds working application.

But when ./src/SimpleComponent returns:

const SimpleComponent = () => {
  return <div>abc</div>;
};

npm run buid command throws exception:

ERROR in ../src/SimpleComponent.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: D:\Tranzystor\webpack-alias-react\src\SimpleComponent.js: Unexpected token (4:9)

How to solve this webpack/Babel configuration issue?

Why is it possible to write <div> in App.js?

Is that right approach?

Whole code is here available.

Upvotes: 1

Views: 1974

Answers (1)

Andrzej
Andrzej

Reputation: 571

I've solved that issues with Babel 7 and extended solution for that kind of issues is there: github

It's ready to use webpack 4 + React + Babel 7 + eslint configuration.

It can be helpful for monorepo solutions.

Publishing your own components library to npm can be another application. As I mentioned above ./src directory contains small react components (content which you want to publish on npm). In ./demo directory there is spa application which shows how to use supplied components (it can be storybook for example).

Upvotes: 2

Related Questions