BreadKiller
V2EX  ›  Vue.js

请教一个静态资源处理的问题

  •  
  •   BreadKiller · Aug 5, 2020 · 2231 views
    This topic created in 2154 days ago, the information mentioned may be changed or developed.

    项目中有个 config.xml 需要在打包后的根目录中,打包后的目录如下:

    • project

      • css

      • js

      • index.html

      • config.xml

    目前的做法是直接把 config.xml 放在 public 的文件夹中以静态资源打包。

    在项目中和这个 config.xml 都有需要用到项目的版本号,我直接在 js 里读取 package.json 的 version,但是在静态资源的这个 config.xml 没办法读取 package.json 的信息。

    所以有没有什么办法可以让这个 config.xml 也能读取到一个全局的 version,这样就不需要每次修改版本号都要修改两个文件了。

    项目是用脚手架 vuecli 生成的

    Supplement 1  ·  Aug 5, 2020

    已解决,解决方法:

    首先把config.xml中的version修改为占位符 {version}

    然后在vue.config.js里添加

    const version = require("./package.json").version;
    module.exports = {
      chainWebpack: (config) => {
        config.plugin("copy").tap((options) => {
          options[0][0].transform = function(content, path) {
            if (/config.xml/.test(path)) {
              content = Buffer.from(content.toString().replace("{version}", version));
            }
            return content;
          };
          return options;
        });
      }
    }
    

    再次感谢回复。

    4 replies    2020-08-05 19:54:52 +08:00
    yhxx
        1
    yhxx  
       Aug 5, 2020
    打包的时候搞个 webpack 插件把 version 直接写进这个 xml 文件里?
    zzk1989
        2
    zzk1989  
       Aug 5, 2020
    楼上已经告诉你了,还有一种方案
    1. vue-cli 有 hooks done ,在里面 configureWebpack 里面注册一个插件在打包完成后用 fs 写文件
    2. npm 脚本也有 post 钩子,新建一个 scripts 在单独的 js 中也能处理 比如"postbuild"
    35aZ4P8mT576683q
        3
    35aZ4P8mT576683q  
       Aug 5, 2020
    config.xml 放上占位符, build script 里面写 linux 命令 (grep + sed 应该就行), 每次 build 自动从 package.json 读取 version 替换 config.xml 里的占位符
    BreadKiller
        4
    BreadKiller  
    OP
       Aug 5, 2020
    @liberty1900 @zzk1989 @yhxx 感谢回复!我看看哪种方便一点
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   998 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 6b34f497 · 48ms · UTC 19:05 · PVG 03:05 · LAX 12:05 · JFK 15:05
    ♥ Do have faith in what you're doing.