'webpack - When should I use require vs import for application.js file
I have hard time understanding the difference between "require" and "import" inside application.js file (Rails 6).
I've got an excerpt of Michael Hartl's book that describes the way to add jquery & bootstrap to my app.
Steps:
yarn add [email protected] [email protected]
then add to config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'
})
)
module.exports = environment
and finally in application.js:
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
import "bootstrap"
The question is - why is jquery required, and bootstrap imported? Thank you,
Update
EDIT - the comment by @arieljuod has helped me to look for solution in javascript realm, I'll leave the question just for future reference. application.js is a javascript file and has nothing to do with rails itself.
Solution 1:[1]
In fact
require
is not a supported natively by browsers (check here and here)- This means that webpack will have to use
import
internally whenever you callrequire
.
- This means that webpack will have to use
compare
import
and dynamic dependency management withrequire
from webpack doc.
Thus: I would use require
for dynamic uses cases as shown in the doc examples and import
everywhere else.
I am not sure if there are any side effects on treeshaking with using require
. The documentation states that it depends on import
and export
Tree shaking is a term commonly used in the JavaScript context for dead-code elimination. It relies on the static structure of ES2015 module syntax, i.e.
import
andexport
.
Just to not for the example with JQuery, the documentation recommends to use ProvidePlugin
here instead:
https://webpack.js.org/plugins/provide-plugin/#usage-jquery
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |