• 在非 Node.js 环境中使用

    在非 Node.js 环境中使用

    vue-server-renderer 在默认构建时,会预先假定有一个 Node.js 环境,这使得它在其他 JavaScript 环境(如 PHP V8Js 或 Oracle Nashorn 中无法使用。在 2.5+ 版本中,我们把那些基本上与环境无关的构建,编译到 vue-server-renderer/basic.js 中,这使得它可以在上述环境中使用。

    对于所有环境,必须要预先在环境中模拟 globalprocess 对象,以及将 process.env.VUE_ENV 设置为 "server" 和将 process.env.NODE_ENV 设置为 "development""production"

    在 Nashorn 环境下,可能还需要使用 Java 原生定时器,来为 PromisesetTimeout 提供 polyfill。

    php-v8js 的示例用法:

    1. <?php
    2. $vue_source = file_get_contents('/path/to/vue.js');
    3. $renderer_source = file_get_contents('/path/to/vue-server-renderer/basic.js');
    4. $app_source = file_get_contents('/path/to/app.js');
    5. $v8 = new V8Js();
    6. $v8->executeString('var process = { env: { VUE_ENV: "server", NODE_ENV: "production" }}; this.global = { process: process };');
    7. $v8->executeString($vue_source);
    8. $v8->executeString($renderer_source);
    9. $v8->executeString($app_source);
    10. ?>

    1. // app.js
    2. var vm = new Vue({
    3. template: `<div>{{ msg }}</div>`,
    4. data: {
    5. msg: 'hello'
    6. }
    7. })
    8. // 通过 `vue-server-renderer/basic.js` 暴露
    9. renderVueComponentToString(vm, (err, res) => {
    10. print(res)
    11. })