运行开发服务器时,外部“ URL”中出现错误“未捕获的ReferenceError:未定义require”

时间:2019-01-31 05:13:03

标签: webpack-4

我刚刚开始研究Webpack,并试图建立基于Webpack4的开发环境。

我在package.json中放置了一个用于执行开发服务器的脚本,如下所示。

package.json

    "scripts": {
        "dev": "webpack-dev-server --mode development",
    }

但是,当我在终端上执行'npm run dev'时,出现如下错误消息。

ERROR in ./node_modules/destroy/index.js
Module not found: Error: Can't resolve 'fs' in 'D:\webpack-setup\node_modules\destroy'
 @ ./node_modules/destroy/index.js 14:17-30

因此,我安装了'webpack-node-externals'并将配置放在'webpack.config.js'中,如下所示。

安装webpack-node-externals模块

    # npm install --save-dev webpack-node-externals

webpack.config.js

    const nodeExternals = require('webpack-node-externals');

    module.exports = {
        target: 'web',
        externals: [nodeExternals()],
        devServer: {
            host: 'localhost',
            port: 3000,
            open: true
        }
    };

打开浏览器时,如下所示的浏览器出现错误。

Uncaught ReferenceError: require is not defined
    at eval (external_"url":1)
    at Object.url (main.js:289)
    at __webpack_require__ (main.js:20)
    at Object.eval (webpack:///(:3000/webpack)-dev-server/client?:6:11)
    at eval (webpack:///(:3000/webpack)-dev-server/client?:249:30)
    at Object../node_modules/webpack-dev-server/client/index.js?http://localhost:3000 (main.js:97)
    at __webpack_require__ (main.js:20)
    at eval (webpack:///multi_(:3000/webpack)-dev-server/client?:1:1)
    at Object.0 (main.js:190)
    at __webpack_require__ (main.js:20)

我不确定此错误是否与'webpack-node-externals'模块有关, 但是我可以得到一些解决这种情况的指南吗?

1 个答案:

答案 0 :(得分:0)

我认为你必须在你的配置文件有问题。我跑的样品与此,它的工作:

const nodeExternals = require('webpack-node-externals')
module.exports = {
  target: 'web',
  externals: [nodeExternals()],
  devServer: {
    host: 'localhost',
    port: 3000,
    open: true,
  },
}