12

我按照本指南创建了我的 npm 模块。我的仓库在 src/assets 文件夹中包含一个 svg 图像(hue-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 将其解释为模块依赖项,如此处所建议的但它不起作用。

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

谢谢您的帮助!

4

2 回答 2

9

我有一个类似的问题,我暂时的解决方法是将以下内容添加到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数据 URL

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

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

于 2019-03-30T19:34:05.770 回答
0

这是使用 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.
于 2019-03-19T13:25:41.617 回答