Sunday, 6 October 2019

Lazy-Loaded vue-router components don't work with SSR

I have two different entry points for server.js and client.js.

If I try importing the route without lazy loading, it works:

import Test from "../views/Test";

export const routes = [{
    path: '/my-route',
    name: "Test",  
    component: Test,
}]

But if I try lazy-loading, it fails on the SSR:

export const routes = [{
    path: '/my-route',
    name: "Test"
    component: () => import('../views/Test.vue'),
}]

var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []

ReferenceError: window is not defined

So when I doing lazy-loading, somehow it's adding window object. :/

I've found this github issue but I couldn't figure out how to do fix it with laravel-mix. For people knowing Laravel-mix, I can add a a webpackConfig like this:

mix.webpackConfig({
   output: {
      chunkFilename: 'js/chunks/[name].js?id=[chunkhash]',
      publicPath: '/',
   }
})

Update:

http://www.compulsivecoders.com/tech/how-to-build-multiple-vendors-using-laravel-mix/ https://github.com/webpack/webpack/issues/7502#issuecomment-443363395

Apparently we can't use laravel-mix to give independent targets for 2 js bundlings, so you either need to build 2 webpack.mix files or bundle them like this. . These 2 links helped me to make 2 bundles and build them separately, however even though it compiled now, SSR with chunks doesn't work.

In my webpack.mix.js:

require('laravel-mix-merge-manifest');

// Creates target specific compiled versions
if (process.env.npm_config_section === 'server') {
    mix.js('resources/js/app-server.js', 'public/js')
        .webpackConfig({ target: 'node' })
        .mergeManifest()
        .version();
} else if (process.env.npm_config_section === 'client') {
    mix.js('resources/js/app-client.js', 'public/js')
        .webpackConfig({ target: 'web' })
        .mergeManifest()
        .version();
} else {
    console.log(
        '\x1b[41m%s\x1b[0m',
        'Provide correct --section argument to build command: server, client'
    );
    throw new Error('Provide correct --section argument to build command!')
}

// Creates target specific chunk
mix.webpackConfig({
    output: {
        chunkFilename: 'js/chunks/' + process.env.npm_config_section + '/[name].js?id=[chunkhash]',
        publicPath: '/',
    },
}

And in my packages.json:

"scripts": {
    "dev-all": "npm --section=server run dev && npm --section=client run dev",
}

By doesn't work, I mean

 <div id="app" data-server-rendered="true"><!----></div>


from Lazy-Loaded vue-router components don't work with SSR

No comments:

Post a Comment