Search code examples
webpackvue-cli-3

modules name Webpack & vue-cli when authoring library


TL;DR;

How to rename webpackChunkName with vue-cli in --target lib mode?


Hi folks, I am authoring a library for Vue js with vue-cli.

This line produces the output of my lib into umd, umd.min & common-js:

vue-cli-service build --target lib --name mylib ./src/components/mylib.vue --dest ./dist

Since my lib has async modules (i18n locales in json files), I want to modify Webpack to control the output of all the files in the final dist folder, but was not successful.

Before I externalize all the locales files for performance, I had this:

dist/
|- mylib.common.js
|- mylib.umd.js
|- mylib.umd.min.js
|- mylib.css

Now that a locale is imported on demand with:

import(/* webpackInclude: /\.json$/, webpackChunkName: "[request]" */ `./i18n/${locale}`)
    .then(response => (this.texts = response.default))

This is the output:

dist/
|- mylib.common.js
|- mylib.umd.js
|- mylib.umd.min.js
|- mylib.css
|- en.common.min.js
|- en.umd.js
|- en.umd.min.js
|- es.common.min.js
|- es.umd.js
|- es.umd.min.js
|- de.common.min.js
|- de.umd.js
|- de.umd.min.js
...

Ideally I would like to get only one locale file for all the versions of my lib as the generated locale files are exactly the same for umd & common-js, and organized in a folder like so:

dist/
|- mylib.common.js
|- mylib.umd.js
|- mylib.umd.min.js
|- mylib.css
|- i18n
   |- en.js
   |- es.js
   |- de.js
   ...

I tried tweaking the import webpack magic comment but got 3 i18n folders like following:

import(/* webpackInclude: /\.json$/, webpackChunkName: "i18n/[request]" */ `./i18n/${locale}`)
    .then(response => (this.texts = response.default))
dist/
|- mylib.common.
   |- i18n
   |- en.js
|- mylib.umd.
   |- i18n
   |- en.js
|- mylib.umd.min.
   |- i18n
   |- en.js

When I add this to my vue.config.js, it modifies the build for my documentation into docs/ (vue-cli-service build), but it does not work for my lib into dist/ (vue-cli-service build --target lib):

  configureWebpack: {
    output: {
      filename: '[name].testing-bundle.js',
      chunkFilename: '[name].testing-bundle.js'
    }
  },

Solution

  • I finally found a suitable workaround!

    I ended up adding a postbuild script (triggered automatically after build) as followed:

    "postbuild-bundle": "rm -rf ./dist/libname.common.i18n ./dist/libname.umd.i18n && mv ./dist/libname.umd.min.i18n ./dist/i18n"