Philipp Chapkovski
Philipp Chapkovski

Reputation: 2069

vue + webpack: how the dynamic component import works?

I use combination of Django+Vue, and I struggle to understand how do names that are created by vue-cli-service build or vue-cli-service serve are created and work, and how to set this in production.

If I do not have dynamic component imports, everything works smoothly.

My vue.config.js looks like that:


module.exports = {
  pages: {
    main: {
      entry: "./src/main.js",
      chunks: ["chunk-vendors"],
    },
  },
  // Should be STATIC_URL + path/to/build
  publicPath: "/front/",
  // Output to a directory in STATICFILES_DIRS
  outputDir: path.resolve(__dirname, "../_static/front/"),

  // Django will hash file names, not webpack
  filenameHashing: false,
  productionSourceMap: false,
  runtimeCompiler: true,
  devServer: {
    writeToDisk: true, // Write files to disk in dev mode, so Django can serve the assets
  },
};

The result of built looks like that: enter image description here

And I simply refer to these files in a Django template:

        <div id="app"></div>
        <script type="text/javascript" src="{% static 'front/js/chunk-vendors.js' %}"></script>
        <script type="text/javascript" src="{% static 'front/js/main.js' %}"></script>

But as soon as I start using dynamic components, like that:

const User = () => import("./components/User")

Everything stops working, and in addition webpack creates some js files with hashed names in a static folder, and I can't figure out the logic (so I can't refer to them in the template.

Upvotes: 0

Views: 1238

Answers (1)

Stiegi
Stiegi

Reputation: 1805

Webpack has so called 'magic comments' - see here https://webpack.js.org/api/module-methods/#magic-comments

What you have there are not really dynamic routes, but lazy ones, which means their code is written into chunks rather than in the main js file and only loaded, when the component is loaded. So to create a named chunk, you can write the import like that:

import(/* webpackChunkName: "about" */ "../views/About.vue")

However, you'll still have a hash value after that. This is done to avoid browser caching - the browser would not know that there is a new version of the file if it has the same name under certain conditions (like no etags set etc.) This is a webpack configuration that can be overwritten in the vue config. You can have a look for that here: https://github.com/vuejs/vue-cli/issues/1649

Edit: as I just saw you can even disable it with the filenamehashing config key: https://cli.vuejs.org/config/#filenamehashing

Upvotes: 1

Related Questions