Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

server render script tag outside of webpack build

Tags:

webpack

I am server rendering my react app like this:

export default ({ clientStats }: { clientStats: any }) => async (req: Request, res: Response, next: any) => {
  const context: any = {};

  const app = (
    <StaticRouter location={req.url} context={context}>
      <Application />
    </StaticRouter>
  );

  if (context.url) {
    res.writeHead(301, {
      Location: context.url
    });

    res.end();
    return;
  }

  const { styles, js, scripts } = flushChunks(clientStats, {
    chunkNames: flushChunkNames()
  });

  const appString = renderToString(app);
  const { title } = Helmet.renderStatic();

  res.status(200).send(`
    <!doctype html>
    <html lang="en">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        ${styles}
        ${title}
      </head>
      <body>
        <div id="root">${appString}</div>
        <script type=\'text/javascript\' src=\'init.js\' defer></script>
      </body>
    </html>
`);
};

How can I reference a script that is outside of the webpack build?

I have an init.js file that does very little and I want to just reference it.

Where can I put it so that when the html is rendered, the script tag resolves?

like image 563
dagda1 Avatar asked Aug 04 '18 07:08

dagda1


1 Answers

It's so simple but a little complicated, first I explain all approach, then show in code.

You should consider a folder for all of JavaScript files that they are out of webpack build. Then put them into this folder and then import it as externals into webpack configuration. then set it as a separate vendor file, and absolutely output file name should make dynamically, so the webpack build its bundle and then copy your JavaScript file into dist folder. follow below:

// webpack.config.js
...
module.exports = {
    ...
    externals: {
        separateFile: `${srcRoot}/outFiles/yourJavaScriptFile.js`,
    },
    ...
};

By using the above code you consider a folder for your JavaScirpt file and import it into webpack configuration as a externals config.

Now you should import it as a separate file alongside your application files. see below:

// webpack.config.js
...
module.exports = {
    ...
    entry: {
        myFile: 'separateFile', // <== its your external imported file
        app: `${srcRoot}/app/index.js`, // <== its your app file
    },
    output: {
        path: '/dist',
        filename: '[name].js' // <== dynamically make your JavaScript files,
                              //      so, in dist folder you can see app.js and
                              //      myFile.js file
    }
    ...
};

Definitely, you should import these files to your template function, hence:

  ...
  res.status(200).send(`
    <!doctype html>
    <html lang="en">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        ${styles}
        ${title}
      </head>
      <body>
        <div id="root">${appString}</div>
        <script src="app.js" defer></script>
        <script src="myFile.js" defer></script>
      </body>
    </html>
 `);
...
like image 89
AmerllicA Avatar answered Oct 11 '22 05:10

AmerllicA