要求未在脚本标记中定义

时间:2018-12-19 19:53:05

标签: javascript reactjs typescript webpack electron

我正在使用针对UI和webpack进行捆绑的react编写电子应用程序。现在为应用程序的react部分配置了Webpack,如下所示:

const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
    mode: 'development',
    entry: './src/index.tsx',
    target:'node',
    output: {
        filename: '[name].bundle.js',
        path: path.join(__dirname, 'build')
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: {
                    loader: 'ts-loader'
                }
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader'
                    }
                ]
            },
            {
                test: /\.css$/,
                loader: 'css-loader',
                options: {
                    sourceMap: true,
                },
            },
            {
                test: /\.scss$/,
                use: [{
                    loader: "css-loader", options: {
                        sourceMap: true
                    }
                }, {
                    loader: "sass-loader", options: {
                        sourceMap: true
                    }
                }]
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: "./index.html",
            filename: "./index.html"
        }),
        new CopyWebpackPlugin([{ from: 'public',ignore: ['*.html'] }])
    ],
    devtool: 'eval-source-map'
}

在我的index.html中,我需要在电子渲染过程中使用以下脚本标签:

<script>
        require('build/bundle.js')
    </script>

当我运行webpack-dev-server时,所有内容都会正确编译,但是当我打开chrome dev工具时,会看到此错误:

Uncaught ReferenceError: require is not defined
    at (index):12

我必须定位webpack.config中的节点以使电子工作,因此我假设require函数也可以在浏览器中工作,因为如果我要在纯node.js环境中创建电子应用(不使用webpack和反应),它无需任何其他配置即可工作。所以我想我的webpack配置有问题,但是很遗憾,我无法在线找到任何有用的资源。谁能帮我吗?提前致谢!

1 个答案:

答案 0 :(得分:0)

Electron基本上是通过«IPC»连接到节点进程的铬浏览器。

这意味着浏览器中没有可用的需求。

您需要这样导入脚本:

<script src="/build/bundle.js"></script>

此外,您还需要将浏览器代码的目标从节点更改为电子渲染器。

如果您还需要为节点侧构建代码,则需要添加电子主靶。

请参见https://webpack.js.org/configuration/