Assets are created in assets
directories, either globally (in assets/
) or on a per-application basis (e.g. in project/partners/assets/
).
The assets
directories contain css/
and js/
subdirectories (or more if needed).
To import code from modules installed through NPM, simply use the module's name.
For example:
import "bootstrap"
For imports in asset files, you can use the @
alias that is defined in webpack.base.conf.js
and points to the project/
folder.
For example:
import "@/partners/assets/js/main.js"
The above imports can also work in SCSS files, but they need to be prepended by a tilde (~
). Read sass-loader's docs for more information:
import "~@/partners/assets/css/main.css";
Our setup currently supports vanilla JS and for stylesheets, CSS and Sass.
There are two ways to include an asset file in Webpack's bundling process:
Scripts that will be used globally in the project are usually imported in the main entry point (assets/js/index.js
).
This also applies to CSS stylesheets, which are additionally splitted to their own files by the mini-css-extract-plugin.
If your asset is to be separated from the rest of the bundles and become its own bundle, you just need to list it as an entry point in Webpack's configuration.
Let's take for example a script assets/js/auth.js
that is necessary only in authorized pages.
In order to create an entry point for it, edit webpack.base.conf.js
and add the following in the entry object:
module.exports = {
...
entry: {
main: fromRoot('assets/js/index.js'),
...,
auth: fromRoot('assets/js/auth.js')
},
...
}
Note:
fromRoot
is a utility function defined inwebpack.base.conf.js
. It simply generates a relative path that points to the root of the repository.
Now when Webpack is run, an auth.js
(or auth-[hash].js
) will be generated in bundles/build-dev/
(or bundles/dist/
). The auth
filename comes from auth
being the corresponding key in entry
, similar to main.js
being the bundle that results from main: fromRoot('assets/js/index.js')
.
The bundling process is simplified by the npm scripts defined in package.json
. Along with the bundles, the webpack-stats
files are also generated.
Generates and stores the bundles in bundles/build-dev/
:
cd bundles
npm run build:dev
Note:
bundles/build-dev/
andwebpack-stats.dev.json
are not to be committed to the repository and thus they are listed inbundles/.gitignore
.
To avoid running npm run build:dev
everytime you make a change you can use the watch mode that does this automatically, by running:
cd bundles
npm run watch
Generates and stores the bundles in bundles/dist/
:
cd bundles
npm run build
Read static files management docs on how to deploy static files when in production mode.
For the simplest case:
{% load render_bundle from webpack_loader %}
<html>
<head>
{% render_bundle 'main' 'css' %}
</head>
<body>
....
{% render_bundle 'main' 'js' %}
</body>
</head>
Check here for extensive examples.