Recently, a new project was started, and it took a long time to configure the project because it had not been created from zero before. Briefly note the biggest pit encountered in configuration: webpack + gulp + babel-loader.
To start with the configuration requirements, the entire project workflow is mainly managed using GULP. Webpack was introduced only to pack compressed JS.
Webpack 2 has Tree Shaking. With the export and import syntax of ES6, you can import only the modules you use and reduce the amount of code that is compressed in the end. After all the documentation and Google configuration examples, gulp + WebPack 2 was finally configured. Try using import to introduce a piece of public code, find also normal import package works, happy feel Voila, done! ^_^
Too young too simple… = =
In the afternoon, my colleague configured the project locally and came to ask me why I only imported one module from the public code (utils.js), but still packaged the whole file. I was like, “Nani, isn’t it written in the document that you pack only import modules?” Why did the document lie to me.
I read the documentation again. There is nothing to configure. Tree shaking is the default. Tree shaking not working tree shaking not working tree shaking not working tree shaking not working tree shaking not working Painting beauty don’t look.. Sure enough, there had already been a great god encountered the same problem.
The problem was caused by the Babel-loader used by Webpack. Babel-loader converts ES6 modules into CommonJS modules, which are then packaged by WebPack. CommonJs modules are dynamic, and WebPack can’t shake out useless code when it’s packaged.
Well, I don’t know what a dynamic module is and what a static module is, but I’ve found the problem. So what’s the solution? Presumably Babel has also discovered this problem and has provided a configuration item to turn off the ES6 Module conversion. Add a configuration to babel-loader:
options: { presets: [ [ 'es2015', { modules: false } ] ] }
Restart Webpack and compress the file again. Sure enough, only the imported module is packed. Modules without import will not be found in the final package of compressed code.
At this point, just finished ~ can happily continue to write code ~
Attached is a link to the article that solved my problem. The great god came across the exact same pit as me and decided to write an article to record it. I was relieved to see more than one person cheated
Blog links to http://varnull.cn/webpack-gulp-babel-loader-config/