复制科尔多瓦准备的额外文件

时间:2020-06-06 17:42:47

标签: cordova

cordova documentation cordova prepare确实做到了:

将config.xml元数据转换为特定于平台的清单文件,复制图标和启动画面,复制指定平台的插件文件,以便可以使用每个本机SDK来构建项目。

我将npm与cordova一起使用,当我运行npm update时,软件包会自动更新。在这种特殊情况下,我使用了npm软件包jquery,其主文件存储在node_modules/jquery/dist/jquery.min.js中。然后,我手动将此文件复制到www/js/res/jquery.min.js,然后通过以下方式将其加载到www/index.html

<script src="js/res/jquery-ui.min.js"></script>

但是我想在cordova prepare中自动执行此过程。

因此,问题是:如何自定义cordova prepare,以便可以将其他文件复制到www目录?

1 个答案:

答案 0 :(得分:0)

仅就我的实现方式提供一些反馈。您必须使用cordova hooks

首先在config.xml

添加以下行
<hook type="after_prepare" src="scripts/importNpmPackages.js" />

然后创建一个执行该任务的节点脚本scripts/importNpmPackages.js,即,将文件从node_modules目录复制到所需的位置。我用这个:

const fse = require('fs-extra')
const path = require('path')

var projectRoot

module.exports = function (context) {
  console.log(context.hook + ': Importing npm packages files')

  projectRoot = path.resolve(path.dirname(context.scriptLocation), '..')
  console.log('Project root directory:', projectRoot)
  copyFile('jquery', path.join('dist', 'jquery.min.js'), path.join('www', 'js', 'res', 'jquery.min.js'))
}

function copyFile (npmPackage, // oficial name of the npm package from which the file is to be copied from
  fileRelativePath, // file path with respect to the main directory of the npm package (node_modules/<package>/)
  destFilePath) { // file's path to where it is copied, relative to the project bin/ directory
  // trick to get the npm module main directory
  // https://stackoverflow.com/a/49455609/1243247
  const packageDirFullpath = path.dirname(require.resolve(path.join(npmPackage, 'package.json')))
  const fileOriginFullPath = path.join(packageDirFullpath, fileRelativePath)
  const fileDestFullPath = path.join(projectRoot, destFilePath)

  fse.copySync(fileOriginFullPath, fileDestFullPath)

  const consoleMsg = npmPackage + ': ' +
    path.relative(projectRoot, fileOriginFullPath) + ' -> ' +
    path.relative(projectRoot, fileDestFullPath)

  console.log(consoleMsg)
}