Palash Chordia
Palash Chordia

Reputation: 147

react js how to import only the required function from a file and not the all functions

this is my functions.js file

export const f1 =()=>
{
console.log('palashf1');
}
export const f2 =()=>
{
console.log('palashf2');
}

and this is the main js file for react application

import {f1} from './functions';

// using f1 somewhere


when I go to console on my webpage and click the bundles I can see that f2 is also getting downloaded

Is there any version of import method that allows us to download only the js function we need and not all the functions of the file from where we are importing ?

creating a separate file for the function is the only solution ??

Upvotes: 5

Views: 1710

Answers (1)

Przemysław Zalewski
Przemysław Zalewski

Reputation: 3986

Please upgrade Webpack to version 2 or newer as it supports tree-shaking which eliminates unused exports.

As Webpack 2 supports native ES6 modules you must disable babel from transpiling ES6 modules to common-js format by configuring babel-loader presets (set modules: false in the es2015 preset):

{
  test: /\.js$/,
  exclude: /node_modules/,
  loader: 'babel-loader',
  options: {
    presets: [
      [
        'es2015', {
          modules: false
        }
      ]
      ...
    ]
  }
}

Tree-shaking should work with this configuration, inspect with the console or Webpack Bundle Analyzer Plugin.

Upvotes: 1

Related Questions