12
votes

I followed this guide to create my npm module. My repo contains in the src/assets folder an svg image (hue-cirle.svg).

When building with vue-cli-service build --target lib --name <lib-name> the svg image is bundled under dist/img/hue-circle123456.svg.

Now when installing the module with npm install --save <module> the path remains src/img/hue-circle123456.svg, while it should refer to the svg image from the node_modules dist folder and not to a non-existing hue-circle123456.svg image from the main Vue App src folder.

Basically what happens is that the svg image path is wrong in the Vue project that uses my module. I tried to add the ~ to force webpack to interpret it as a module dependency as suggested here but it did not work.

In the end I gave up and embedded the svg in the html template as you can see in the repo. Nonetheless, I ask this question since I could not find any solution and I, as well as others, may need to solve this in order to use image resources in custom modules built with vue-cli-service build --target lib --name <lib-name> command.

Thanks for the help!

2
I'm surprised no one has answered this yet :/Acidic9
I don't think alias will fix this. When I check the bundle file after build as lib. I found my image was webpack.__require__ and the path is localhost:8080/xxx/my-image But when I use the lib as a dependency in my project1, I saw the image request but there is no real image data responded with a success code 200Xiaojing Zhao

2 Answers

9
votes

I have a similar problem, my fix for the time being is to add the following to vue.config.js:

module.exports = {
  css: {
    extract: false
  },
  chainWebpack: config => {
    config.module
      .rule("images")
      .use("url-loader")
      .loader("url-loader")
      .tap(options => Object.assign(options, { limit: Infinity }));
  }
};

This inlines all assets as base64 Data URLs.

Taken from: https://cli.vuejs.org/guide/html-and-static-assets.html#relative-path-imports

Edit:

For SVG try this:

module.exports = {
  css: {
    extract: false
  },
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()

    svgRule
      .test(/\.svg$/)
      .use('svg-url-loader') // npm install --save-dev svg-url-loader
      .loader('svg-url-loader')
  }
};

Remember this is far from optimal and a workaround!

0
votes

Here is the documentation for resolve path with WebPack :

https://webpack.js.org/configuration/resolve/

The path for assets can be resolve like this for example :

process.env.NODE_ENV == "production ? path.resolve(process.cwd(), "dist/assets") : path.resolve(__dirname, "src/assets");

Production :

process.cwd() // Where the application is running. You can pack it for example.