webpack reactjs应用程序加载失败:Uncaught ReferenceError:未定义snapapp

webpack reactjs app fails to load: Uncaught ReferenceError: snapapp is not defined

本文关键字:Uncaught ReferenceError 未定义 snapapp 失败 reactjs 应用程序 加载 webpack      更新时间:2023-09-26

这是一个最小的reactjs应用程序,当使用webpack捆绑并运行时,会从浏览器控制台发出以下错误:

Uncaught ReferenceError: snapapp is not defined

有人能提出原因吗?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body class='section'>
<div id="app"></div>
<script type="text/javascript" src="./build/snapapp.js"></script>
<script type="text/javascript">
    (function () {
        var mountNode = document.getElementById('app');
        snapapp.start(mountNode);
    })();
</script>
</body>
</html>

index.js

import { render } from 'react-dom';
import rootLayout from './src/components/ApplicationLayout.jsx';
import hello from './src/components/hello.jsx';
export function start(mountNode) {
  render(<rootLayout />, mountNode);
}

webpack.config.js

var path = require('path');
var webpack = require('webpack');
module.exports = {
  entry: './index.js',
  output: {
    path: 'build',
    filename: 'snapapp.js',
    libraryTarget: "umd"
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  }
};

src/components/hello.jsx

import React from 'react';
class Hello extends React.Component {
  render() {
    return <h1>Hello</h1>
  }
}

您正在从模块导出snapapp,但您没有在任何地方导入/需要它,它不是作为全局变量存在的。

您正在以UMD文件格式导出。如果你需要在index.html文件中内联代码,那么你需要使用像Require这样的库

您可以选择的替代方案:

输出到var

umd更改为var,您可以在此处阅读,这将把您的库添加到window全局对象中。允许您像在html文件中一样调用它。

output: {
    path: 'build',
    filename: 'snapapp.js',
    libraryTarget: "var"
}

将启动脚本放入文件包

除非有特殊原因,否则我会将引导脚本移到您的index.js文件中。没有理由不能从文件中获取装载点。这也是你试图做的事情的一个非常常见的模式

import { render } from 'react-dom';
import rootLayout from './src/components/ApplicationLayout.jsx';
import hello from './src/components/hello.jsx';
render(<rootLayout />, document.getElementById('app'));