【问题标题】:"require is not defined" Using webpack 2“要求未定义”使用 webpack 2
【发布时间】:2017-06-04 06:20:37
【问题描述】:

我在使用 webpack 捆绑我的应用时遇到了问题,我在网站上看到了类似的问题,尽管我已经尝试了所有建议,但我无法找出问题所在。

一切都很好。但是,当我打开浏览器时,会显示此错误:
Uncaught ReferenceError: require is not defined

webpack-dist.conf.js

const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const FailPlugin = require('webpack-fail-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const pkg = require('../package.json');
const autoprefixer = require('autoprefixer');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  module: {
    loaders: [
      {
        test: /\.json$/,
        loaders: [
          'json-loader'
        ]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        enforce: 'pre'
      },
      {
        test: /\.(css|scss)$/,
        loaders: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?minimize!sass-loader!postcss-loader'
        })
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: [
          'ng-annotate-loader',
          'babel-loader'
        ]
      },
      {
        test: /\.html$/,
        loaders: [
          'html-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    FailPlugin,
    new HtmlWebpackPlugin({
      template: conf.path.src('index.html')
    }),
    new webpack.optimize.UglifyJsPlugin({
      output: {comments: false},
      compress: {unused: true, dead_code: true, warnings: false} // eslint-disable-line camelcase
    }),
    new ExtractTextPlugin('index-[contenthash].css'),
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor'}),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: () => [autoprefixer]
      }
    })
  ],
  target: 'node',
  externals: [nodeExternals()],
  output: {
    path: path.join(process.cwd(), conf.paths.dist),
    filename: '[name]-[hash].js'
  },
  entry: {
    app: `./${conf.path.src('index')}`,
    vendor: Object.keys(pkg.dependencies)
  }
};

package.json

{
  "dependencies": {
  "angular": "^1.6.2",
  "angular-ui-router": "1.0.0-beta.3",
  "body-parser": "^1.17.2",
  "cookie-parser": "^1.4.3",
  "debug": "^2.6.8",
  "express": "^4.15.3",
  "morgan": "^1.8.2",
  "pug": "^2.0.0-rc.2"
},
"devDependencies": {
  "@types/angular": "^1.6.6",
  "@types/angular-mocks": "^1.5.9",
  "@types/angular-ui-router": "^1.1.36",
  "@types/jquery": "^2.0.40",
  "angular-mocks": "^1.6.2",
  "autoprefixer": "^6.7.3",
  "babel-core": "^6.23.1",
  "babel-eslint": "^7.1.1",
  "babel-loader": "^6.3.2",
  "babel-plugin-istanbul": "^4.0.0",
  "babel-polyfill": "^6.23.0",
  "babel-preset-es2015": "^6.22.0",
  "babel-preset-es2017": "^6.24.1",
  "bootstrap": "^4.0.0-alpha.6",
  "browser-sync": "^2.18.8",
  "browser-sync-spa": "^1.0.3",
  "css-loader": "^0.26.4",
  "del": "^2.2.2",
  "es6-shim": "^0.35.3",
  "eslint": "^3.15.0",
  "eslint-config-angular": "^0.5.0",
  "eslint-config-xo-space": "^0.15.0",
  "eslint-loader": "^1.6.1",
  "eslint-plugin-angular": "^1.6.1",
  "eslint-plugin-babel": "^4.0.1",
  "extract-text-webpack-plugin": "^2.0.0-rc.3",
  "file-loader": "^0.11.1",
  "font-awesome": "^4.7.0",
  "gulp": "gulpjs/gulp#4ed9a4a3275559c73a396eff7e1fde3824951ebb",
  "gulp-angular-filesort": "^1.1.1",
  "gulp-angular-templatecache": "^2.0.0",
  "gulp-filter": "^5.0.0",
  "gulp-htmlmin": "^3.0.0",
  "gulp-hub": "frankwallis/gulp-hub#d461b9c700df9010d0a8694e4af1fb96d9f38bf4",
  "gulp-insert": "^0.5.0",
  "gulp-ng-annotate": "^2.0.0",
  "gulp-sass": "^3.1.0",
  "gulp-util": "^3.0.8",
  "html-loader": "^0.4.4",
  "html-webpack-plugin": "^2.28.0",
  "jasmine": "^2.5.3",
  "jquery": "^3.2.1",
  "json-loader": "^0.5.4",
  "karma": "^1.4.1",
  "karma-angular-filesort": "^1.0.2",
  "karma-coverage": "^1.1.1",
  "karma-jasmine": "^1.1.0",
  "karma-junit-reporter": "^1.2.0",
  "karma-ng-html2js-preprocessor": "^1.0.0",
  "karma-phantomjs-launcher": "^1.0.2",
  "karma-phantomjs-shim": "^1.4.0",
  "karma-webpack": "^2.0.2",
  "mdbootstrap": "^4.3.2",
  "ng-annotate-loader": "^0.2.0",
  "node-sass": "^4.5.0",
  "phantomjs-prebuilt": "^2.1.14",
  "postcss-loader": "^1.3.1",
  "sass-loader": "^6.0.1",
  "style-loader": "^0.13.1",
  "tether": "^1.4.0",
  "url-loader": "^0.5.8",
  "webpack": "^2.2.1",
  "webpack-fail-plugin": "^1.0.5",
  "webpack-node-externals": "^1.6.0"
},
"scripts": {
"start": "node app.js",
"build": "gulp",
"serve": "gulp serve",
"serve:dist": "gulp serve:dist",
"test": "gulp test",
"test:auto": "gulp test:auto"
},
"eslintConfig": {
"globals": {
  "expect": true
},
"root": true,
"env": {
  "browser": true,
  "jasmine": true
},
"parser": "babel-eslint",
"extends": [
  "xo-space/esnext"
  ]
}
}

如果有人能提供帮助,我将不胜感激。

【问题讨论】:

    标签: javascript webpack babeljs


    【解决方案1】:

    您使用的target 不正确:

    target: 'node'
    

    这意味着该捆绑包旨在用于 Node.js(服务器端)程序,而不是浏览器。您可以将其更改为web,或者直接删除该行(因为web 是默认值)。

    【讨论】:

    • 问题依旧
    • 如果webpack-node-externals 是针对浏览器的,则不应使用它。它将依赖项转换为单个 require 调用。删除target : 'node之后的下一行
    • target 应设置为 web 并且 externals 应留空,除非您使用的库不是捆绑包,例如来自 CDN 等的 jQuery
    • @StijndeWitt 如果您使用的是捆绑的库怎么办?
    • 解决了我的问题!非常感谢。
    【解决方案2】:

    部分配置需要更改:

    target: 'web', // which is by default // externals: [nodeExternals()], remove this as it is causing problem

    【讨论】:

    • 如果你删除它,你将如何添加你需要的模块??
    • Webpack 会在你的包中包含模块代码。所以像往常一样只是require('some-lib'),你会看到some-lib的源代码被从node_modules中拉出来并添加到你的bundle.js中。
    【解决方案3】:

    在使用 node + express 和托管小部件构建后端以供客户端使用时遇到此问题。我的 webpack 配置分为两种,一种用于后端,一种用于前端。

    const webpack = require('webpack');
    const path = require('path');
    const nodeExternals = require('webpack-node-externals');
    
    const config = {
      // set to false because __dirname resolving to / instead of absolute path when
      // built using webpack
      node: {
        __dirname: false
      },
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['es2015']
              }
            }
          }
        ]
      },
      // set to development to read .env.local variables
      mode: 'development'
    };
    
    const serverConfig = Object.assign({}, config, {
      // set target to node to fix build warnings
      target: 'node',
      name: 'server',
      entry: __dirname + '/src/index.js',
      output: {
        path: path.resolve(__dirname + '/dist'),
        filename: 'index.js'
      },
      // webpack-node-externals package used to exclude other packages like express
      // in the final bundle.js
      externals: [nodeExternals()]
    });
    
    // widget.js file served from dist/widget
    const widgetConfig = Object.assign({}, config, {
      // set target to web for use in browsers
      target: 'web',
      name: 'widget',
      entry: __dirname + '/widget/index.js',
      output: {
        path: path.resolve(__dirname + '/dist/widget/js'),
        filename: 'widget.js'
      }
    });
    
    module.exports = [widgetConfig, serverConfig];
    

    【讨论】:

    • 你拯救了我的一天!最后根据您的提示创建了一个功能齐全的服务器和客户端呈现的网页。
    猜你喜欢
    • 2023-03-10
    • 2019-03-19
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多