vue-cli-service build --target lib 在导入为 lib 时丢失图像路径

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

我关注这个 guide to create my npm module. My repo 在 src/assets 文件夹中包含一个 svg 图像(色调-cirle.svg)。

使用 vue-cli-service build --target lib --name <lib-name> 构建时,svg 图像捆绑在 dist/img/hue-circle123456.svg 下。

现在,当使用 npm install --save <module> 安装模块时,路径仍然是 src/img/hue-circle123456.svg,而它应该引用 node_modules dist 文件夹中的 svg 图像,而不是不存在的 hue-circle123456.svg 图片来自主 Vue App src 文件夹。

基本上发生的事情是在使用我的模块的Vue项目中svg图像路径是错误的。我试图添加 ~ 以强制 webpack 将其解释为建议的模块依赖项 here 但它不起作用。

最后我放弃了并将 svg 嵌入到 html 模板中,正如您在 repo 中看到的那样。尽管如此,我问这个问题是因为我找不到任何解决方案,我和其他人可能需要解决这个问题才能在使用 vue-cli-service build --target lib --name <lib-name> 命令构建的自定义模块中使用图像资源。

感谢您的帮助!

这是使用 WebPack 解析路径的文档:

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

资产的路径可以这样解析,例如:

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

制作:

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

我也有类似的问题,我暂时的解决方法是在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 }));
  }
};

这会将所有资产内联为 base64 Data URLs

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

编辑:

对于 SVG,试试这个:

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')
  }
};

请记住,这远非最佳解决方案!