在没有 Ionic 的设备上进行 Cordova 热重载

Cordova hot reloading on device without Ionic

我使用的是没有 Ionic 或任何其他框架的 Cordova。我的问题是,如果不使用 Ionic,我找不到适用于 Cordova 的任何热重载功能或插件。有什么解决方案可以在没有任何框架的情况下在 iOS 模拟器上实时重新加载吗?

我在 Cordova 中实现了 'hot reloading' 的自定义方式。我不知道它有多原始,但它很适合我的需要。 概括地说,它是这样工作的:在开发模式下,启动一个静态网络服务器,并指示 cordova 内容是该服务器的 url:<content src="http://10.0.3.2:8080" />.

静态服务器还监听资产的变化(js/css/html)和自动重新加载。我们使用gulp connect(https://www.npmjs.com/package/gulp-connect)来实现。

在生产模式下,您必须编译资产并指示 cordova 使用常规静态文件加载您的应用程序。

详情:

cordova.xml 中,这是告诉 cordova 在何处启动应用程序的行:

<content src="index.html" />

因此必须将其替换为允许热重载的 'dynamic' 版本。我通过使用启动静态文件服务器的 gulp-connect 实现了这一点。

  gulp.task('connect', function () {
    return connect.server({
      root: 'www',
      livereload: true,
      fallback: 'www/index.html',
      https: false
    });
  });

我创建了两个任务来切换开发和生产中的 cordova 配置:

  // Development
  // adds the localhost(on the emulator as 10.0.3.2) as
  // the content source for the cordova app
  gulp.task('cordova-dev-server-android', function () {
    return gulp.src(['config.xml'])
      .pipe(replace(/(<content src=\")(.+)(\" \/>)/g, "http://10.0.3.2:8080"))
      .pipe(gulp.dest('.'));
  });

  // Production
  // adds the static file as
  // the content source for the cordova app
  gulp.task('cordova-static-file', function () {
    return gulp.src(['config.xml'])
      .pipe(replace(/(<content src=\")(.+)(\" \/>)/g, "index.html"))
      .pipe(gulp.dest('.'));
  });

您必须确保 Cordova javascript 文件可由开发 Web 服务器访问,这很重要。同样,我通过 development/production.

的两个任务实现了这一点
  // Development
  // Creates symlinks for the devserver
  // so the app has access to cordova files
  gulp.task('create-cordova-symlink-android', ['remove-cordova-symlink'], function () {
    return gulp.src('')
      .pipe(exec('ln -sv ../platforms/android/assets/www/cordova.js www'))
      .pipe(exec.reporter())
      .pipe(exec('ln -sv ../platforms/android/assets/www/cordova_plugins.js www'))
      .pipe(exec.reporter())
      .pipe(exec('ln -sv ../platforms/android/assets/www/plugins www'))
      .pipe(exec.reporter());
  }); 


  // Production
  // Removes symlinks for production
  // see create-cordova-symlink-android
  gulp.task('remove-cordova-symlink', function () {
    var options = {
      continueOnError: true
    };
    return gulp.src('')
      .pipe(exec('rm www/cordova.js', options))
      .pipe(exec('rm www/cordova_plugins.js', options))
      .pipe(exec('rm -Rf www/plugins', options));
  });

我在这里使用 gulp 但这可以使用任何任务运行程序来实现,当然对于其他平台,您必须稍微修改此代码。

希望对您有所帮助。