Recently when I was practicing writing React and Vue, I would import the same file multiple times in different subcomponents, for example: Import React from ‘React’, import Vue from ‘Vue’, etc. My gut tells me that Webpack is not stupid. It’s not stupid to pack so many times that the packed files become bloated. If not, why not? After searching Google with curiosity for a long time, I failed to find a convincing answer, so I did an experiment (source) to prove my guess:

1. Simulate the React/Vue environment

The first step is to install the related webpack, Babel and other related dependencies and set up the directory webpack Settings:

//webpack.config.js
module.exports = {
  entry: './app.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    loaders:[
      {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        loader: 'babel-loader?presets[]=es2015&presets[]=react'
      },
    ]
  }
}
Copy the code

Package. json Required dependencies:

/ / package. Json {" name ":" test ", "version" : "0.0.1", "devDependencies" : {" webpack ":" ^ 1.14.0 "}, "dependencies" : {" Babel - core ", "^ 6.21.0", "Babel - loader" : "^ 6.2.10", "Babel - preset - es2015" : "^ 6.18.0", "Babel - preset - react" : "^ 6.16.0}}"Copy the code

Other files for testing:

//demo.js-- equivalent to vue export default {test(argu) {console.log(argu)}} //test1.js -- equivalent to a component import demo from './demo' Export default {test1() {demo.test(1)}} //test2.js -- equivalent to another component import demo from './demo' export default {test1() { //add.js import Test1 from './ Test1 'import Test2 from './ Test2' test1.test1 () test2.test2 ()Copy the code

I’ll import demo.js in both test1.js and test2.js, and exoprt will import methods that depend on demo.js in app.js. Test2.js webpack, open bundle.js, and find the demo section.

bundle.js
__webpack_require__(num)
import
demo.js
2

Webpack does not import the same file multiple times from different files, but only references the corresponding function of the packaged file multiple times in the packaged file.

Finally clear up the problem, very comfortable!! 👻