0

According to cordova documentation cordova prepare does:

Transforms config.xml metadata to platform-specific manifest files, copies icons & splashscreens, copies plugin files for specified platforms so that the project is ready to build with each native SDK.

I use cordova with npm and when I run npm update the packages are updated automatically. In this particular case I used npm package jquery whose main file is stored at node_modules/jquery/dist/jquery.min.js. Then I manually copy this file to www/js/res/jquery.min.js and then I load it at www/index.html by:

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

But I want to automate this process in cordova prepare.

Thus the question is: how can you customise your cordova prepare, such that you can copy extra files to www directory?

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109

1 Answers1

0

Just to give some feedback on how I achieved it. You must use cordova hooks.

First add the following line at config.xml

<hook type="after_prepare" src="scripts/importNpmPackages.js" />

Then create a node script scripts/importNpmPackages.js that does the job, i.e, copy files from node_modules directory to where you want. I use this one:

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

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109