[Vuejs]-How to force npm to instanciate only one copy of a dependecy from two different projects

0👍

After digging around and looking at vue-router for inspiration, I managed to get it running. So if anyone has this problem, here is the solution I’ve found, regarding what to add to the json files of the library:

  • Put your declaration file in types/index.d.ts
  • tsconfig.json:
...
"include": [
  ...  
  "types/index.d.ts"
],
  • package.json:
...
"main": "dist/**Your Lib Name**.common.js", // you can add module etc. for other relevant outputs
"scripts": {
  ...
  "build": "vue-cli-service build --target lib --name **Your Lib Name** src/main.ts",
},
"typings": "types/index.d.ts",
"files": [
  "src",
  "dist/*.js",
  "types/*.d.ts"
],
  • run npm build
  • copy folders dist, types and package.json to node_modules/Your Lib Name in the project you want to use your library

I think npm link does not work because it includes the node_modules folder under the library, resulting in two copies of, in this case, vue, but I am not sure.

Regarding vue, if you want to make your life easier and let typescript generate the declaration files for you, add the following:

  • tsconfig.json:
...
"declaration": true,
"declarationDir": "types_tmp/",
  • vue.config.js:
...
configureWebpack: config => {
  if(process.env.NODE_ENV === 'production') {
    config.module.rules.forEach(rule => {
      if (rule.use) {
        let idx = rule.use.findIndex(w => w.loader === 'thread-loader')
        if (idx !== -1) rule.use.splice(idx, 1)
      }
    })
  }
},
chainWebpack: config => {
  if(process.env.NODE_ENV === 'production') {
    // disable cache (not sure if this is actually useful...)
    config.module.rule("ts").uses.delete("cache-loader");
    config.module.rule("tsx").uses.delete("cache-loader");

    config.module
    .rule('ts')
    .use('ts-loader')
    .loader('ts-loader')
    .tap(opts => {
      opts.transpileOnly = false;
      opts.happyPackMode = false;
      return opts;
    });
  }
}
  • merge the relevant .d.ts files into types/index.d.ts

Hope it helps someone,

Leave a comment