VueJS SSR V8JS Symfonybug Jquery - PullRequest
       19

VueJS SSR V8JS Symfonybug Jquery

0 голосов
/ 04 марта 2019

У меня установлена ​​VueJS / Symfony и V8JS для SSR (SEO frendly). Установите V8JS, все в порядке, но у меня конфликт с Jquery

V8Js::compileString():2246: TypeError: Cannot read property 'jquery' of undefined

Я оставляю вам важный код.Я использую Jquery и axios для некоторых вещей.

Но я не могу так сильно волноваться с Jquery.Я думаю, что мне нужно добавить конфигурацию, чтобы избежать конфликта с Jquery, но невозможно знать, что поставить

Если бы у кого-то было решение моей проблемы, было бы замечательно

РЕДАКТИРОВАТЬ КОД:06-03-19

* WebPack Config JS (конфигурация Webpack JS Encore)

let Encore = require('@symfony/webpack-encore');
 Encore
 // the project directory where compiled assets will be stored
.setOutputPath('public/build/')
// the public path used by the web server to access the previous directory
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
// uncomment to create hashed filenames (e.g. app.abc123.css)
// .enableVersioning(Encore.isProduction())

// uncomment to define the assets of the project
.addEntry('entry-client', './assets/js/entry-client.js')
.addEntry('entry-server', './assets/js/entry-server.js')
.addEntry('js/app', './assets/js/app.js')
.addEntry('css/app', './assets/css/app.scss')
// uncomment if you use Sass/SCSS files
.enableSassLoader()
// uncomment for legacy applications that require $/jQuery as a global variable
//.autoProvidejQuery()

// Enable Vue Loader
.enableVueLoader();

module.exports = Encore.getWebpackConfig();

app.js (App.js)

// require jQuery normally
const $ = require('jquery');
require('bootstrap');

global.axios = require('axios');

require('../css/app.css');
require('bootstrap-sass');


import Vue from 'vue';

import Motdepasse from './components/Motdepasse'

/**
 * Create a fresh Vue Application instance
*/
new Vue({
    el: '#app',
    components: {Motdepasse}
});

export function createApp() {
  return new Vue({
    render: h => h(Motdepasse)
  });
}

клиент входа

        import { createApp } from './app'
        createApp().$mount('#app');

сервер ввода

        import { createApp } from './app'
    renderVueComponentToString(createApp(), (err, res) => {
      print(res);
    });

app.scss

@import '~bootstrap-sass/assets/stylesheets/bootstrap';
@import 'app.css';

app.css

body {
    background-color: white!important;
}

контроллер по умолчанию

class DefaultController extends AbstractController
{
    /**
     * @Route("/", name="default")
     */
    public function index()
    {       $ssr = $this->renderJs();
        return $this->render('default/index.html.twig', [
            'controller_name' => 'DefaultController','ssr' => $ssr 
        ]);
    }


    private function renderJs()
{
    $renderer_source = file_get_contents(__DIR__ . '/../../node_modules/vue-server-renderer/basic.js');
    $app_source = file_get_contents(__DIR__ . '/../../public/build/entry-server.js');
    $v8 = new \V8Js();
    ob_start();
    $v8->executeString('var process = { env: { VUE_ENV: "server", NODE_ENV: "production" }}; this.global = { process: process };');
    $v8->executeString($renderer_source);
    $v8->executeString($app_source);
    return ob_get_clean();
}
}

Package.json

    {
    "devDependencies": {
        "@symfony/webpack-encore": "^0.20.1",
        "bootstrap": "^4.3.1",
        "bootstrap-sass": "^3.3.7",
        "jquery": "^3.3.1",
        "node-sass": "^4.9.3",
        "popper.js": "^1.14.7",
        "sass-loader": "^7.1.0",
        "vue": "^2.5.17",
        "vue-loader": "14.2.2",
        "vue-template-compiler": "^2.5.17",
        "webpack-notifier": "^1.6.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production"
    },
    "dependencies": {
        "axios": "^0.18.0",
        "moment": "^2.22.2",
        "vue-server-renderer": "^2.6.8"
    }
}

1 Ответ

0 голосов
/ 05 марта 2019

Удалить эту строку

global.jQuery = require ('jquery');

Поскольку Webpack Encore уже предоставляет Jquery относительно этой строки:

.autoProvidejQuery ()

Подробнее, здесь

РЕДАКТИРОВАТЬ

Относительно вашей новой ошибки

V8Js :: compileString (): 2241: Ошибка: JavaScript Bootstrap требует jQuery

Убедитесь, что у вас установлена ​​Bootstrap

 yarn add bootstrap --dev

После Bootstrapтребуется Jquery и Popper, вам необходимо установить его

yarn add jquery popper.js --dev

Затем попробуйте еще раз.

Если это не сработает, попробуйте запросить библиотеку в начале JS-файла

const $ = require('jquery'); // this "modifies" the jquery module: adding behavior to it // the bootstrap module doesn't export/return anything 
require('bootstrap');

Дополнительная информация, Импорт начальной загрузки официальной документации Symfony

РЕДАКТИРОВАНИЕ 2 (относительно добавленного исходного кода)

В приложении.scss, замените эту строку

@ import '~ bootstrap-sass / assets / stylesheets / bootstrap';

на эту:

@import "~bootstrap/scss/bootstrap";
...