首页 > 解决方案 > 未捕获的 ReferenceError:未定义 Webpack + AngularJS

问题描述

像这样的问题有几十个,但没有一个有帮助,因为根本原因总是我没有做。我正在使用 webpack 4.26.1 为浏览器制作一个捆绑包,Uncaught ReferenceError: require is not defined无论我做什么,当我在浏览器中打开 web 应用程序时,我都会收到。

我没有使用target: 'node'.

我不需要webpack-node-externals.

我没有明确排除捆绑包中的任何内容。

我没有使用noParse.

我什至尝试显式设置target: 'web',即使它是默认设置,只是为了看看是否有任何改变。

这是我的全部内容webpack.config.json

const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/main/webapp/resources/app/template.core.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'src/main/webapp/resources/dist')
  }
};

这是我的 package.json

{
  (...)
  "main": "src/main/webapp/template.core.js",
  "dependencies": {
    "angular": "^1.6.10",
    "angular-animate": "^1.6.10",
    "angular-route": "^1.6.10",
    "angular-sanitize": "^1.6.10",
    "angular-upload": "^1.0.13",
    "ui-select": "^0.19.8",
    "angular-ui-bootstrap": "^2.5.0",
    "moment": "2.22.2"
  },
  "devDependencies": {
    "npm": "^5.6.0",
    "webpack": "^4.26.1",
    "webpack-cli": "^3.1.2",
    "jshint": "^2.9.6"
  },
  "scripts": {
    "lint": "jshint src/main/webapp --exclude src/main/webapp/resources/static,src/main/webapp/resources/dist",
    "build": "webpack"
  },
  (...)
}

我究竟做错了什么?

标签: javascriptnpmwebpackrequirecommonjs

解决方案


为了将来参考,我的问题与在 html 中包含错误一样基本<script>,因为由于我的 webpack 配置,包的文件名对于开发和生产模式是不同的。我现在html-webpack-plugin用来生成包含,我的模板文件是一个只有注释的空文件,所以它只输出脚本标签本身。这是它在我的外观webpack.config.js

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

module.exports = {

  ...

  plugins: [
    new HtmlWebpackPlugin({
      template: 'path/to/empty/template',
      filename: 'path/to/templated/output'
    })
  ],

  ...

};

推荐阅读