How to tell web pack to use external js file url without freezing in in bundle?

Viewed 892

There is a simple task: I want to try making a Google Chromecast receiver app (which is SPA). Google Chromecast SDK (cast SDK) requires their framework to be on external url. Also this framework creates global cast object.

What is the correct way of creating this webpack application? The targets I want to achieve:

  • Build index.html with HtmlWebpackPlugin
  • Develop using import this framework (import cast from ???)
  • Avoid bundling it (probably using externals)?
  • Ensure cast object created by this js file is global (ProvidePlugin?)
  • Add <script src="http://cdn....js"></script> into HTML created by HtmlWebpackPlugin

For now I am trying to setup simple app, and I got stuck on last step - adding <script> tag to output html, but I'm sure that there are mistakes I've done on prev steps.

Could you help guiding me through this process?


My current webpack.config.js is:
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      { test: /\.svg$/, use: 'svg-inline-loader' },
      { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] },
      { test: /\.(js)$/, use: 'babel-loader' }
    ]
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      scriptLoading: 'defer',
      hash: true,
      
    }) ,
    new webpack.ProvidePlugin({
      cast: path.resolve(path.join(__dirname, 'src/cast_receiver_framework'))
    }) 
  ],
  mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
  devServer: {
    compress: false,
    disableHostCheck: true
 },
 externalsType: 'script',
 externals: {
  cast_receiver_framework: ['//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js', 'cast']
 }
}
1 Answers

To solve your last step you can use the template param of HtmlWebpackPlugin to customize your template.

By default HtmlWebpackPlugin will inject bundled modules at the end of the <body>.

Check the documentation if you need further customization.


index.html


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <!-- Whatever else you might need -->
    </head>
    <body>
        <div id="your-mount-point-id"></div>

        <script src="http://cdn....js"></script>
    </body>
</html>

webpack.config.js

plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__dirname, "path/to/index.html"),
        scriptLoading: 'defer',
        hash: true,
    })
],
Related