首页 > 解决方案 > 在 `npm build` 的输出中添加源路径前缀

问题描述

我使用 vue-cli 创建了一个小型 vue 应用程序。我npm run build用来制作 UI 的生产版本,最终得到一堆 CSS、js 和一个包含所有这些 js 和 CSS 文件的 HTML 页面文件。但是,为了应用程序的目的,需要将 HTML 移动到不同的目录,中间件可以访问该目录。这就是为什么需要在 js 和 CSS 文件的 URL 前加上前缀,以指向新的目录。是否可以在 js 和 CSS 文件的输出 HTML 文件中创建前缀?

以下是 的内容package.json

{
  "name": "investmentapp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "bootstrap": "^4.5.3",
    "bootstrap-vue": "^2.18.1",
    "core-js": "^3.6.5",
    "vue": "^2.6.11",
    "vue-class-component": "^7.2.3",
    "vue-property-decorator": "^8.4.2"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.33.0",
    "@typescript-eslint/parser": "^2.33.0",
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-typescript": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-typescript": "^5.0.2",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "typescript": "~3.9.3",
    "vue-template-compiler": "^2.6.11"
  }
}

PS 目前,我已经编写了一个单独的脚本来自动执行此操作,但我正在寻找一个内置选项。另外,我很想将其构建到npm run serve.

标签: vue.jsnpmnpm-scripts

解决方案


您可以通过添加可以在构建和服务中重用的“复制”脚本来复制 package.json 脚本中的文件。

  "scripts": {
    "serve": "vue-cli-service serve && npm run copy",
    "build": "vue-cli-service build && npm run copy",
    "lint": "vue-cli-service lint",
    "copy": "cp src/*.html destinationDir"
  },

至于为 CSS 和 JS 网址添加前缀,假设您使用的是 webpack,您可以在 webpack.config.js 中进行。类似的东西:

output: {
  filename: '../PrefixDir/[name].[chunkhash].js',
  ...
},

推荐阅读