Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ??

like image 318
Palash Chordia Avatar asked Nov 07 '22 21:11

Palash Chordia


1 Answers

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.

like image 131
Przemysław Zalewski Avatar answered Nov 15 '22 11:11

Przemysław Zalewski