TransWikia.com

How should the script tag in a react page be written to include it properly with webpack?

Stack Overflow Asked on December 16, 2021

I am trying to include react in my HTML page. At first I tried like this:

<script src="js/custom/custom.js"></script>

But that syntax gives me the following error:

Uncaught SyntaxError: Cannot use import statement outside a module

So I added the module attribute:

<script type="module" src="js/custom/custom.js"></script>

But with that, webpack isn’t able to resolve the module path correctly, giving me this error:

Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

I have set up webpack with a custom entry path like so:

const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: './js/custom/custom.js',
    output: {
        path:  path.join(__dirname, '/build'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: path.join(__dirname, '/'),
        port: 9000
    },

2 Answers

The problem is that that script element is pointing to the raw, uncompiled source script, instead of the output script which webpack generates. It needs to point to webpack's output script so that it will be run through babel, compiled, compressed, etc.

The correct path to webpack's output script is the dev server address, plus the filename specified in webpack.config.js output filename. Thus, if config looks like:

module.exports = {
    output: {
        filename: 'badoongy-face.js'
    },

Then the script tag should be:

<script src="https://localhost:8000/badoongy-face.js"></script>

or the same thing as a relative path:

<script src="badoongy-face.js"></script>

Answered by brentonstrine on December 16, 2021

html-webpack-plugin is thing you need

check this out

The plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags. Just add the plugin to your webpack configuration as follows:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

...
plugins: [new HtmlWebpackPlugin()]
..

Check how you can add custom template

Answered by Kalhan.Toress on December 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP