Home > Enterprise >  How can I import modules onto Webpack?
How can I import modules onto Webpack?

Time:12-22

I have installed webpack to use with Flask. When my app.js file looks like this:

import "../styles/index.scss";
import "bootstrap/dist/js/bootstrap.bundle";
import "../components/sidebar";

window.document.addEventListener("DOMContentLoaded", function () {
  window.console.log("dom ready 12");
  console.log("Ggg");
});

everything works normally. But when I add

import "jquery/dist/jquery.min.js";

Then this file is not read anymore, eventhough the webpack watch process isn't throwing any errors. I know the file is not read because the console logs I run in it no longer appear in the browser console. Why is that?

Tried various variations of the import code:

import * as $ from 'jquery';
window.$ = $;
import * as $ from 'jquery/dist/jquery.min';
window.$ = $;
import * from "jquery/dist/jquery.min.js";

Etc. But I can't seem to find the right one.

EDIT:

I have also tried using the Provide Plugin (as suggested in the first Answer below, see my comment there), however to no avail. This is how my webpack.common.js file looks like:

const glob = require("glob");
const Path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const WebpackAssetsManifest = require("webpack-assets-manifest");

const getEntryObject = () => {
  const entries = {};
  glob.sync(Path.join(__dirname, "../src/application/*.js")).forEach((path) => {
    const name = Path.basename(path, ".js");
    entries[name] = path;
  });
  return entries;
};
var webpack = require("webpack");

module.exports = {
  entry: getEntryObject(),
  output: {
    path: Path.join(__dirname, "../build"),
    filename: "js/[name].js",
    publicPath: "/static/",
    assetModuleFilename: "[path][name][ext]",
  },
  optimization: {
    splitChunks: {
      chunks: "all",
    },

    runtimeChunk: "single",
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new CopyWebpackPlugin({
      patterns: [
        { from: Path.resolve(__dirname, "../vendors"), to: "vendors" },
      ],
    }),
    new WebpackAssetsManifest({
      entrypoints: true,
      output: "manifest.json",
      writeToDisk: true,
      publicPath: true,
    }),
  ],
  resolve: {
    alias: {
      "~": Path.resolve(__dirname, "../src"),
    },
  },
  module: {
    rules: [
      {
        test: /\.mjs$/,
        include: /node_modules/,
        type: "javascript/auto",
      },
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        type: "asset",
      },
    ],
  },
};

Relevant lines in my HTML code are:

{{ javascript_pack('app', 'app2', attrs='charset="UTF-8"') }}
<script>$('#my-select')</script>

manifest.json:

{
  "app.css": "/static/css/app.css",
  "app.js": "/static/js/app.js",
  "app2.js": "/static/js/app2.js",
  "entrypoints": {
    "app": {
      "assets": {
        "js": [
          "/static/js/runtime.js",
          "/static/js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js-node_modules_jquery_dist_jquery_js.js",
          "/static/js/app.js"
        ],
        "css": [
          "/static/css/app.css"
        ]
      }
    },
    "app2": {
      "assets": {
        "js": [
          "/static/js/runtime.js",
          "/static/js/app2.js"
        ]
      }
    }
  },
  "js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js-node_modules_jquery_dist_jquery_js.js": "/static/js/vendors-node_modules_bootstrap_dist_js_bootstrap_bundle_js-node_modules_jquery_dist_jquery_js.js",
  "runtime.js": "/static/js/runtime.js",
  "vendors/.gitkeep": "/static/vendors/.gitkeep",
  "vendors/images/.gitkeep": "/static/vendors/images/.gitkeep",
  "vendors/images/sample.jpg": "/static/vendors/images/sample.jpg",
  "vendors/images/webpack.png": "/static/vendors/images/webpack.png"
}

CodePudding user response:

Unfortunately, jQuery is one of those plugins that get messed up in webpack's bundling process.

The recommended (and easiest) way to get jQuery working is to use the ProvidePlugin.

Inside your webpack.config.js, add the following block to the plugins array -

new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
});

If you don't have a plugins array, just add the array as follows -

... // other configurations
plugins: [
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
    });
],

Edit 1: Try using cacheGroups inside splitChunks as follows -

splitChunks: {
  cacheGroups: {
    vendor: {
      test: /node_modules/,
      name: "vendor",
      chunks: "all",
      enforce: true,
    },
  },
},

This will ensure that ONE vendor.js file is created - hopefully the manifest file and/or browser won't have a tough time importing that file.

Edit 2: Switch to url_for() to possibly fix it.

<script src="{{ url_for('static', filename='js/vendor.js') }}"></script>
<script src="{{ url_for('static', filename='js/runtime.js') }}"></script>
<script src="{{ url_for('static', filename='js/app.js') }}"></script>
<script src="{{ url_for('static', filename='js/app2.js') }}"></script>
  • Related