vue-cli-service build --target lib loses images path when imported as lib

泪湿孤枕 提交于 2020-05-10 14:29:21

问题


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!


回答1:


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!




回答2:


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.


来源:https://stackoverflow.com/questions/51523450/vue-cli-service-build-target-lib-loses-images-path-when-imported-as-lib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!