Frontend
Why Webpack
Note
webpack is an open-source JavaScript module bundler. It is made primarily for JavaScript, but it can transform front-end assets such as HTML, CSS, and images if the corresponding loaders are included
Webpackis the most popular bundle solution in the frontend community today, it has received 50k stars on Github.- It has a great ecosystem, many plugins, loaders. If we search
webpackon npmjs.com, we can get 20k resulst. - If we do not need
React,Vue, we can still use Webpack to help us compileES6,SCSSand do many other things (Many people do not know that!) - With a proper config, Webpack can save time and let us build modern web application in quick way.
Structures
After creating frontend project from the template, you will have file structures like this.
frontend
├── package.json
├── src
│ ├── application
│ ├── components
│ └── styles
├── vendors
│ └── images
│ ├── sample.jpg
│ └── webpack.png
- Components can be placed at
src/components - SCSS and CSS code can be put at
src/styles - Static assets such as images, fonts and other files can be put at
vendors
Compile
Note
If you have no nodejs installed, please install it first by using below links
- On nodejs homepage
- Using nvm I recommend this way.
# install dependency packages
$ npm install
# run webpack in watch mode
$ npm run watch
You will see build directory is created under frontend directory
manifest.jsoncontains assets manifest info.- We can get the dependency of the entrypoint through
manifest.json - So in templates, we can only import entrypoint without dependency files.
For example, {{ javascript_pack('app', attrs='charset="UTF-8"') }} would generate HTMl like this
<script type="text/javascript" src="/static/js/runtime.js" charset="UTF-8"></script>
<script type="text/javascript" src="/static/js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js.js" charset="UTF-8"></script>
<script type="text/javascript" src="/static/js/app.js" charset="UTF-8"></script>
appis entrypoint file/static/js/runtime.jsand/static/js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js.jsare all dependency files.javascript_packhelps us import bundle files transparently
NPM commands
There are three npm commands for us to use
npm run watch
npm run watch would run webpack in watch mode.
webpack can watch files and recompile whenever they change
npm run start
npm run start will launch a server process, which makes live reloading possible.
If you change JS or SCSS files, the web page would auto refresh after the change. Now the server is working on port 9091 by default, but you can change it in webpack/webpack.config.dev.js
npm run build
production mode, Webpack would focus on minified bundles, lighter weight source maps, and optimized assets to improve load time.
What should I use
- If you are developing, use
npm run watchornpm run start - You should use
npm run buildin deployment