How to Start Webpack
by mmyoji
3 min read
One of my participating projects uses Gulp for bundling front-end JavaScript and
CSS in a part even in 2020. It uses browserify internally, but the gulpfile
is
really messy and I will try to migrate it to webpack build which I've been
avoided. And I've found the key points to use Webpack and leave a note.
Dependencies
You should check your package versions and each document because the usage may differ per version of package.
In my experiment, I use the following versions:
- webpack v4.41.5
- webpack-cli v3.3.10
- babel-loader v8.0.6
- uglifyjs-webpack-plugin v2.2.0
- vue-loader v15.8.3
babel-loader
For most people, (IMO) this loader settings can be a demon's gate (meaning a hard part to start with). The usage of it has changed from v7 (Upgrade to Babel 7 · Babel) and some says a slightly different things because of this change. So you need to translate the settings when you google.
Normally, babel's settings can be put in babel.config.js
, .babelrc.json
or
"babel"
key in package.json
(Config Files · Babel), but you can
also do it in webpack.config.js
directly. I tried a little, the
webpack.config.js
settings is prior to normal babel setting files.
For the target browsers, you can use
browserslist. This package
(settings) can be shared with other build tools like Autoprefixer and
postcss-preset-env, etc. You write this settings in .browserslistrc
or
"browserslist"
key in package.json
.
I think it's okay to set up browserslist
to extract ES5 compatible code (for
support IE11), there are babel plugins like
@babel/plugin-transform-runtime
or
@babel/plugin-transform-arrow-functions.
The usage of @babel/plugin-transform-runtime
is a bit hard and you should see
the documentation when you need to use it.
uglifyjs-webpack-plugin
This is mainly used to minify bundles (just my understanding).
If you fail minify process, your extracted code is not ES5 compatible because this package supports ES5 not ES6 nor later. If you don't need to support ES5, you can use TerserWebpackPlugin | webpack instead.
vue-loader
If you don't use Vue.js for your project, you skip this part.
From the v13, you have to change code of CommonJS module system require
.
(Release v13.0.0 · vuejs/vue-loader)
// before v13
const MyButton = require("./MyButton.vue");
// v13~
const MyButton = require("./MyButton.vue").default;
This is ridiculous and you should use ES6 module system (import/export
) for
the target code of webpack.
It also changed from v14, see Migrating from v14 | Vue Loader.
Helpful Reference
Make use of long-term caching | Web Fundamentals | Google Developers
This page is so useful to learn REAL webpack usage for beginners like me :)
Conclusion
When you start a new project, you should avoid writing webpack.config.js
directly as much as possible because you can use create-next-app
or
create-nuxt-app
.
I'm not familiar with modern front-end and if you find any mistakes in this post, please tell me on twitter!