Which one to choose with webpack:
import $ from 'jquery';
or
var $ = require('jquery');
and how to import or require a file that does not have anything to export as such (only helpers functions)?
Also is var $ =
mandatory when using the require('jquery');
method?
Depending on whether you're using babel-loader
or not.
If you don't want to write in ECMA6+/JSX syntax, you are browser-safe to go with older CommonJS/node.js require('jquery');
syntax.
If you're want to support newer syntaxes like ECMA6, ECMAscript-2015, ECMA7, JSX etc., you'd probably want to go with babel-loader
and ECMA6 import syntax
. Be careful about import default vs named vs alias vs wildcard import though, you might want to use syntaxes:
import {jQuery as $} from 'jquery';
or
import $ from 'jquery';
More on ways to import jquery here.
If you don't want to import any particular name from the module (e.g. if you import jQuery
just to let it adds itself to global window.jQuery = window.$
), you can just say import 'jquery';
.
To enable babel-loader
in webpack, use configuration like:
webpack.config.js
{
entry: 'app.js',
output: {
path: path.join(__dirname, 'dist'),
publicPath: publicPath,
filename: outputFilename
},
resolve: {
modules: [path.join(__dirname, 'src'), path.join(__dirname, 'node_modules')]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
],
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react'],
plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']
}
},
...
]
...
}
}
Note also that you can use webpack ProvidePlugin, as I did in this config to shim jQuery for modules that expect it available as a global variable.