Search code examples
reactjswebpackminifybundling-and-minificationbabel-loader

Issue with minifying transpiled `jsx` code into browser readable format


I have to host a js file on a server to be imported into any html page. We have written some react components for the same purpose.

When we import the un-minified js file in the html, it works fine.

But, when we use the minified js file, it doesn't work. That means, it doesn't show anything in the browser.

We are using webpack for bundling the react components. yarn build

Babel-loaders to transpile the jsx code to js

I have tried to manually transpile the jsx code and then minify it. In this case the minified file also works.

But, it doesn't work when I transpile it through the my project config.

The difference between the manually minified and the projects minified file was that the manually minified file has the reference of the js files where React components are written.

.babelrc

{
  "presets": [
    ["latest"],
    "es2015",
    "flow",
    "react",
    "stage-2",
  ],
  "plugins": [
    "syntax-dynamic-import",
  ],
  "env": {
    "production": {
      "plugins": [
        "transform-react-remove-prop-types",
        "transform-react-inline-elements"
      ]
    },
    "development": {
      "plugins": [
        "transform-react-jsx-source"
      ]
    },
    "test": {
      "presets": [
        ["latest"],
        "es2015",
        "flow",
        "react",
        "stage-2",
      ],
      "plugins": [
        "syntax-dynamic-import",
        "transform-react-jsx-source"
      ]
    }
  }
}

webpack.config.js

const path = require('path');
const paths = require('./webpack.paths.js');
const loaders = require('./webpack.loaders.js');
const plugins = require('./webpack.plugins.js');

module.exports = {
  entry: [path.resolve(paths.embed, 'index.js')],
  output: {
    path: paths.productionRoot,
    filename: 'filename.js',
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: Object.assign({}, {
      'react': 'preact-compat',
      'react-dom': 'preact-compat',
    }),
  },
  module: {
    loaders: [
      loaders.eslint,
      loaders.iFrameJs,
      loaders.css,
    ],
  },
  plugins: [
    plugins.environmentVariables,
  ],
};

Solution

  • I changed the webpack config and removed the below piece of code.

    alias: Object.assign({}, {
       'react': 'preact-compat',
       'react-dom': 'preact-compat',
    }),
    

    The react and preact version mismatch was causing the problem.

    New webpack config

    module.exports = {
      entry: [path.resolve(paths.embed, 'index.js')],
      output: {
        path: paths.productionRoot,
        filename: 'termly.js',
      },
      resolve: {
        extensions: ['.js'],
      },
      module: {
        loaders: [
          loaders.eslint,
          loaders.js,
          loaders.css,
        ],
      },
      plugins: [
        plugins.environmentVariables,
      ],
    };

    This solved the issue