簡體   English   中英

未捕獲的 ReferenceError:未在 webpack 設置上定義要求

[英]Uncaught ReferenceError: require is not defined on webpack setup

我在 webpack 周圍玩耍並做出反應。

基本上,我的src文件夾下有兩個文件utils.jsapp.js文件。

這是我的utils.js文件的內容:

const square = (x) => x * x;

export { square };

這是我的app.js文件:

import { square } from './utils.js';

console.log('i Hello from app.js here!');

console.log(square(4));

當我通過yarn run build運行我的應用程序時,它給了我這個錯誤:

app.js:3 Uncaught ReferenceError: require is not defined
    at app.js:3

我檢查了我的webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
      path: path.join(__dirname, 'public'),
      filename: 'bundle.js'
  }
};

我覺得我做得很好。 我的代碼有什么問題? 是什么意思?

您正在嘗試在瀏覽器中使用 CommonJS 模塊。 這行不通。 你如何使用它們? 當你在 ES6 中編寫 import... from... 時,Babel 會將這些調用轉換為一個名為 CommonJS 的模塊定義,並且由於 CommonJS 不在瀏覽器中,你會從 require() 中得到一個未定義的錯誤。 如果您想在代碼庫中使用 CommonJS 模塊,您需要首先將它們與 Browserify 或 webpack 捆綁在一起。 這兩個工具會將您的 require 調用轉換為可以在瀏覽器中使用的一些膠水魔術。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM