exports is not defined webpack 4

9
我正在使用Webpack 4来打包应用程序资源。
tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "types":  ["node"], 
    "typeRoots": [
      "../node_modules/@types"
    ]
  },
    "compileOnSave": true,
    "exclude": [
       "node_modules"    
    ]
}

webpack.config.js:

module.exports = require("./config/webpack.dev.js");

webpack.common.js:

//common webpack configuration
var webpack = require("webpack");
var path = require("path");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
var helpers = require("./helpers.js");

module.exports = {
//the entry-point files that define the bundles
entry: {
    "polyfills": "./scripts/polyfills.ts",
    "vendor": "./scripts/vendor.ts",
    "main": "./scripts/main.ts"
},
//resolve file names when they lack extensions
resolve: {
    extensions: [".ts", ".js"]
},
target: "node",
//decide how files are loaded
module: {
    rules: [
        {
            test: /\.ts$/,
            loaders: [
                {
                    loader: "awesome-typescript-loader",
                    options: {
                        configFileName: helpers.root("./scripts", "tsconfig.json")
                    }                        
                }, "angular2-template-loader"
            ]
        },
        {
            test: /\.html$/,
            loader: "html-loader"
        },
        {
            test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
            loader: "file-loader?name=assets/[name].[hash].[ext]"
        },
        {
            test: /\.css$/,
            exclude: helpers.root("./scripts", "app"),
            loader: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader?sourceMap" })
        },
        {
            test: /\.css$/,
            include: helpers.root("./scripts", "app"),
            loader: "raw-loader"
        }
    ]
},
plugins: [
    // Workaround for angular/angular#11580
    new webpack.ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /\@angular(\\|\/)core(\\|\/)esm5/,
        helpers.root("./scripts"), // location of your src
        {} // a map of your routes
    ),
    //replaced by optimization.splitChunks for webpack 4
  //        new webpack.optimize.CommonsChunkPlugin({
  //            name: ["app", "vendor", "polyfills"]
  //        }),

    new HtmlWebpackPlugin({
        template: "./Views/Shared/_Layout.cshtml",
        filename: "index.cshtml",
        alwaysWriteToDisk: true
    }),
    new HtmlWebpackHarddiskPlugin({            
    })
],
optimization: {
    splitChunks : {
        chunks: "async",
        minSize: 30000,
        minChunks: 1,
        maxAsyncRequests: 5,
        maxInitialRequests: 3,
        automaticNameDelimiter: '~',
        name: true,
        cacheGroups: {
            vendors: {
                test: /[\\/]node_modules[\\/]/,
                priority: -10
            },
            default: {
                minChunks: 2,
                priority: -20,
                reuseExistingChunk: true
            }
        }
    }
   }
  }

webpack.dev.js:

//development webpack configuration
var webpackMerge = require("webpack-merge");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var commonConfig = require("./webpack.common.js");
var helpers = require("./helpers.js");

   module.exports = webpackMerge(commonConfig, {
devtool: "cheap-module-eval-source-map",

output: {
    path: helpers.root("Views"),
    publicPath: "scripts/",
    filename: "[name].js",
    chunkFilename: "[id].chunk.js"
},

plugins: [
    new ExtractTextPlugin("[name].css")
],

devServer: {
    historyApiFallback: true,
    stats: "minimal"
}
});

我正在使用 Angular5,并遵循官方的快速入门指南构建 webpack 配置。使用 `npm start` 命令(开发配置)成功编译 webpack,并且 `index.cshtml` 注入了我想要的 3 个文件:
1. `polyfills.js` 2. `vendor.js` 3. `main.js`
问题在于,当这些文件从浏览器加载时,我会收到以下错误信息:
polyfills.ts:2 Uncaught ReferenceError: exports is not defined
at polyfills.ts:2
(anonymous) @ polyfills.ts:2
vendor.ts:1 Uncaught ReferenceError: exports is not defined
at vendor.ts:1
(anonymous) @ vendor.ts:1
main.js:2 Uncaught ReferenceError: exports is not defined
at main.js:2
(anonymous) @ main.js:2

有人能帮我解决配置出了什么问题吗?
6个回答

7
将以下内容添加到 Babel 插件配置中将解决此问题:
["@babel/plugin-transform-modules-commonjs"]

这个插件将 ECMAScript 模块转换为 CommonJS。OP 需要相反的操作。 - Dotista

6

在我的 Webpack 4 设置(使用 Babel 7)中,出现了一个看起来非常相似的错误。Webpack 正确地构建了包,但是当我尝试加载文件时,出现了以下错误:

Uncaught ReferenceError: exports is not defined
at eval (util.js:22)

…其中util.js是我自己的库之一。 我搜索了很多解决方案,建议使用babel-loader配置 modules: false 和/或 sourceType: unambiguous,并且/或在output中设置 libraryTarget(为'umd'),因此我尝试了以下类似的方法:

{test: /\.js$/, use:
     {
         loader: 'babel-loader',
         options:
         {
             presets: [
                 ['@babel/preset-env', {loose: true, modules: false}],
                 '@babel/react'
             ],
             sourceType: 'unambiguous'
         }
     }
}

我需要在我的webpack.config.js文件的rules部分进行设置。以上建议的任何组合对我都没有起作用。

最终,问题其实很简单,只需更改以下内容(来自于我自己的util.js文件的末尾):

exports.foo = foo;
exports.boo = boo;

… 至:

export {foo, boo};

我附上了我的(可用的)webpack.config.jspackage.json

webpack.config.js

'use strict';
const path = require('path');

const APPDIR = 'app/';

const HtmlWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
    template: path.resolve(__dirname, APPDIR, 'index.html'),
    filename: 'index.html',
    inject: 'body'
});

const config = {
    context: path.resolve(__dirname, APPDIR),
    entry: './main.js',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {test: /\.js$/, use:
             {
                 loader: 'babel-loader',
                 options:
                 {
                     presets: [
                         ['@babel/preset-env'], '@babel/react'
                     ]
                 }
             }
            },{
                test: /\.css$/,
                use: [
                    // style-loader
                    {loader: 'style-loader'},
                    // css-loader
                    {loader: 'css-loader',
                     options: {
                         modules: true
                     }
                    }]
            },{
                test: /\.(png|jpg|jpeg|gif|woff)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192
                        }
                    }]
            },{
                test: /\.README$/,
                use: 'null-loader'
            }
        ]
    },
    plugins: [HTMLWebpackPluginConfig],

    node: {
        fs: "empty" // This is to account for what appears to be a bug: https://github.com/josephsavona/valuable/issues/9`
    }
};

module.exports = config;

package.json

{
"name": "cubehelix-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
    "clean": "rm -fr build/index.html && rm -fr build/bundle.js && npm run clean-logs",
    "build": "webpack --progress --colors",
    "build-min": "webpack --config=webpack.min.config.js",
    "dev": "webpack-dev-server --devtool eval --progress --colors --content-base build --port 8090",
    "test-build": "mkdir -p lib && babel app --out-dir lib --source-maps",
    "test": "npm run test-build && mocha --require source-map-support/register --compilers js:babel-register"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
    "@babel/cli": "~7.6.0",
    "@babel/core": "~7.6.0",
    "@babel/preset-env": "~7.6.0",
    "@babel/preset-react": "^7.0.0",
    "@babel/register": "~7.6.0",
    "@babel/runtime": "~7.6.0",
    "babel-loader": "^8.0.6",
    "chai": "~4.2.0",
    "css-loader": "^0.23.1",
    "file-loader": "^0.9.0",
    "html-webpack-plugin": "~3.2.0",
    "mocha": "~6.2.0",
    "null-loader": "^0.1.1",
    "style-loader": "^0.13.0",
    "url-loader": "^0.5.7",
    "webpack": "~4.39.3",
    "webpack-cli": "^3.3.8",
    "webpack-dev-server": "~3.8.0"
},
"dependencies": {
    "chai": "~4.2.0",
    "classnames": "^2.2.5",
    "jquery": "~3.4.1",
    "lodash": "~4.17.15",
    "prop-types": "^15.7.2",
    "react": "~16.9.0",
    "react-custom-validators": "*",
    "react-dom": "~16.9.0",
    "react-timer-mixin": "~0.13.4"
}
}

一个简单的 export {foo, boo}; 对我很有用。感谢那个简单的解决方案。 - John Skoumbourdis
终于解决了!<3 永远不要使用 export.bla = function() {},而是始终使用 export {myfunction1, myfunction2} 来解决这个问题。 - poitroae
1
sourceType: 'unambiguous' 让我找到了解决方案,这就是我所需要的。有关 webpack 5 / babel 7,请参见 https://github.com/webpack/webpack/issues/4039#issuecomment-419284940 的原理说明。 - Geoff Williams

1

这个选项在v7中被删除了,因为它已经成为默认设置。 - Andreas Richter

0

不确定这是否会对任何人有所帮助,因为我们有一个非常“特殊”的设置,我们遇到了这个问题。

我们看到的是,通过 package.json/npm link 中的 file:/ 引用的符号链接共享库(有效地)与 dist 目录一起被 webpack 错误地转译。

我们在 webpack 的“resolve”部分中指定了“symlinks: true”选项,并且我们的解决方法是添加到相关的 module.rules[] 部分中的 ignore 部分。

我认为这是因为,即使文件在 node_modules 中具有符号链接并且已经跟随,但解析后的路径使得忽略模式无法找到它们,它们再次被错误地转译。

diff --git a/project/webpack.config.js b/project/webpack.config.js
index f688472d72..a680c205e7 100644
--- a/project/webpack.config.js
+++ b/project/webpack.config.js
@@ -265,7 +265,10 @@ function webpackConfig(_target) {
        rules: [
          {
            test: /\.jsx?$/,
-            exclude: /node_modules/,
+            exclude: [
+              /node_modules/,
+              /node-lib/
+            ],
            use: {
              loader: 'babel-loader',
              options: {

(我们的共享库出现在与project同级的目录node-lib中)


0

我也遇到了这个错误。对我来说,问题是我不小心在我的main.ts旁边放了一个main.js,导致webpack使用那个文件而不是main.ts,并且由于某种原因没有发出许多导入的模块。删除main.js解决了这个问题。


-1

你不一定需要改变任何代码。你可以使用 babel 或其他转译器来为你完成这个任务。 - Domi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接