应该如何编写 React 页面中的脚本标签以将其正确包含在 webpack 中?

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

我正在尝试在我的 HTML 页面中加入 React。起初我是这样尝试的:

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

但是该语法给我以下错误:

Uncaught SyntaxError: Cannot use import statement outside a module

所以我添加了模块属性:

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

但是,webpack 无法正确解析 module path,给我这个错误:

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

我已经使用自定义入口路径设置了 webpack,如下所示:

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
    },

html-webpack-plugin 是你需要的东西

检查this

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

问题是脚本元素指向原始的、未编译的源脚本,而不是 webpack 生成的输出脚本。需要指向webpack的输出脚本,这样才会运行通过babel,编译,压缩等

webpack 输出脚本的正确路径是开发服务器地址,加上 webpack.config.js 输出文件名中指定的文件名。因此,如果配置看起来像:

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

那么脚本标签应该是:

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

或与相对路径相同的东西:

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