导出未定义webpack 4

时间:2018-04-27 07:30:07

标签: webpack

我正在使用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

任何人都可以帮我解决配置问题吗?

3 个答案:

答案 0 :(得分:3)

我在Webpack 4设置(使用Babel 7)中出现了一个非常类似的错误。 Webpack正在正确构建捆绑包,但是当我尝试加载文件时,我得到了:

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

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

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

…在我的rules的{​​{1}}部分中。上述建议的排列对我没有任何作用。 最后,只需更改以下内容(从我自己的webpack.config.js文件的末尾开始)即可:

util.js

…至:

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

我附加我的(工作中的)export {foo, boo}; webpack.config.js

webpack.config.js

package.json

package.json

'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;

答案 1 :(得分:1)

这是一个可能的解决方案(这对我来说是“未定义导出”错误):https://github.com/webpack/webpack/issues/3974#issuecomment-369260590

  

无论如何,我的解决方案是在['transform-runtime',{“ polyfill”:false}]插件下更改babel-loader配置

答案 2 :(得分:0)

将此添加到babel config插件将解决此问题:

report