在ReferenceError

时间:2017-12-15 04:24:41

标签: javascript npm webpack babeljs

我最近更新到webpack 3.10.0和Babel 6.26。 虽然我能够修复我的开发构建,但由于某种原因我无法弄清楚我的prod构建失败。

这是我得到的错误:

ERROR in ./src/index.js
Module build failed: ReferenceError: [BABEL] J:\project\src\index.js: Using removed Babel 5 option: foreign.modules - Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules    at Logger.error (J:\project\node_modules\babel-core\lib\transformation\file\logger.js:41:11)
at OptionManager.mergeOptions (J:\project\node_modules\babel-core\lib\transformation\file\options\option-manager.js:220:20)
at J:\project\node_modules\babel-core\lib\transformation\file\options\option-manager.js:265:14
at J:\project\node_modules\babel-core\lib\transformation\file\options\option-manager.js:323:22
at Array.map (native)
at OptionManager.resolvePresets (J:\project\node_modules\babel-core\lib\transformation\file\options\option-manager.js:275:20)
at OptionManager.mergePresets (J:\project\node_modules\babel-core\lib\transformation\file\options\option-manager.js:264:10)
at OptionManager.mergeOptions (J:\project\node_modules\babel-core\lib\transformation\file\options\option-manager.js:249:14)
at OptionManager.init (J:\project\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
at File.initOptions (J:\project\node_modules\babel-core\lib\transformation\file\index.js:212:65)
at new File (J:\project\node_modules\babel-core\lib\transformation\file\index.js:135:24)
at Pipeline.transform (J:\project\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
at transpile (J:\project\node_modules\babel-loader\lib\index.js:50:20)
at J:\Permateam\node_modules\babel-loader\lib\fs-cache.js:118:18
at ReadFileContext.callback (J:\project\node_modules\babel-loader\lib\fs-cache.js:31:21)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:366:13)

我按照错误消息中的建议阅读了http://babeljs.io/docs/plugins/#modules

但对我来说,看起来我正在做所有正确的事情。

有人可以告诉我在webpack.config.js中无法转换的内容吗?

var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

var webpack = require('webpack');
var path = require('path');

var ProvidePlugin = require("webpack/lib/ProvidePlugin");
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
var LimitChunkCountPlugin = require("webpack/lib/optimize/LimitChunkCountPlugin");
var DedupePlugin = require("webpack/lib/optimize/DedupePlugin");
var CleanWebpackPlugin = require('clean-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CircularDependencyPlugin = require('circular-dependency-plugin');
var CompressionPlugin = require('compression-webpack-plugin');

var BUILD_DIR =  path.resolve(__dirname,'dist');

var APP_DIR = path.resolve(__dirname, 'src');
var CLIENT_DIR = path.resolve(__dirname, 'src/client');

// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});

var PrintChunksPlugin = function() {};
PrintChunksPlugin.prototype.apply = function(compiler) {
    compiler.plugin('compilation', function(compilation, params) {
        compilation.plugin('after-optimize-chunk-assets', function(chunks) {
            console.log(chunks.map(function(c) {
                return {
                    id: c.id,
                    name: c.name
/*,
                    includes: c.modules.map(function(m) {
                        return m.request;
                    })
*/
                };
            }));
        });
    });
};

var config = {
    devtool: 'cheap-module-source-map',
    entry: {
        app: APP_DIR + '/index.js'
    },

    output: {
        path:BUILD_DIR,
        filename: "[name].bundle.js",
        sourceMapFilename: "[name].bundle.js.map",
        chunkFilename: "[name]-chunk.js",
        //publicPath: BUILD_DIR
    },

  watch: false,
  watchOptions: {
    poll: true,
    aggregateTimeout: 300
  },
  module : {
    rules: [
    {
              test : /\.jsx?/,
              include : APP_DIR,
              exclude: /node_modules/,

              use: [
          {
            loader: 'react-hot-loader/webpack'
          },
          {
            loader: 'babel-loader?' + JSON.stringify({
              cacheDirectory: true,
              plugins: [
                'transform-runtime',
                'react-html-attrs',
                'transform-class-properties',
                'transform-decorators-legacy'
                ],
              presets: [
                'env',
                {
                  "modules": false
                },
                'react',
                'stage-2']
              })
          }
      ]
          },

          // CSS
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader turns CSS into JS modules that inject <style> tags.
          // In production, we use a plugin to extract that CSS to a file, but
          // in development "style" loader enables hot editing of CSS.
          {
              test: /\.css$/,
              include: path.join(__dirname, 'src/style'),

        use: [
          'style-loader',
          'css-loader'
        ]
          },

          // "file" loader makes sure those assets get served by WebpackDevServer.
          // When you `import` an asset, you get its (virtual) filename.
          // In production, they would get copied to the `build` folder.
          {
              test: /\.(ico|jpg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
              exclude: /\/favicon.ico$/,

        use: [
          {
              loader: 'file-loader',
              query: {
                name: '[path][name][hash].[ext]',
                publicPath: '/'
              }
          }
        ]
          },

          {
              test: /\.(ico)(\?.*)?$/,
              exclude: /node_modules/,
        use: [
          {
              loader: 'file-loader',
              query: {
                  name: './images/[name].[ext]'
              }
          }
        ]
          },

          {
              test: /\.xml$/,

        use: [
          {
              loader: 'file-loader',
              query: {
                  name: './[name].[ext]'
              }
          },
        ]
      }
      ]
  },

     // use EnableCircularDependencyPlugin=true|false to check the option
  plugins: (function() {
        var plugins = [
              new webpack.DefinePlugin({
                  // A common mistake is not stringifying the "production" string.
                  'process.env': { 'NODE_ENV': JSON.stringify('production') },

                  // DISABLE redux-devtools HERE
                  __DEVTOOLS__: false 
              }),

            new CopyWebpackPlugin([
                { from: APP_DIR + '/index.html', to: BUILD_DIR + '/index.html' },
                { from: APP_DIR + '/sitemap.xml', to: BUILD_DIR + '/sitemap.xml' },
                { from: APP_DIR + '/Robots.txt', to: BUILD_DIR + '/Robots.txt' },
                { from: APP_DIR + '/images/favicon.ico', to: BUILD_DIR + '/images/favicon.ico' },
                { from: APP_DIR + '/images/favicon.png', to: BUILD_DIR + '/images/favicon.png' },
                { from: APP_DIR + '/images/favicon-16x16.png', to: BUILD_DIR + '/images/favicon-16x16.png' },
                { from: APP_DIR + '/images/favicon-32x32.png', to: BUILD_DIR + '/images/favicon-32x32.png' },
                { from: APP_DIR + '/images/favicon-48x48.png', to: BUILD_DIR + '/images/favicon-48x48.png' },
                { from: APP_DIR + '/images/favicon-57x57.png', to: BUILD_DIR + '/images/favicon-57x57.png' },
                { from: APP_DIR + '/images/favicon-60x60.png', to: BUILD_DIR + '/images/favicon-60x60.png' },
                { from: APP_DIR + '/images/favicon-72x72.png', to: BUILD_DIR + '/images/favicon-72x72.png' },
                { from: APP_DIR + '/images/favicon-76x76.png', to: BUILD_DIR + '/images/favicon-76x76.png' },
                { from: APP_DIR + '/images/favicon-96x96.png', to: BUILD_DIR + '/images/favicon-96x96.png' },
                { from: APP_DIR + '/images/favicon-114x114.png', to: BUILD_DIR + '/images/favicon-114x114.png' },
                { from: APP_DIR + '/images/favicon-120x120.png', to: BUILD_DIR + '/images/favicon-120x120.png' },
                { from: APP_DIR + '/images/favicon-144x144.png', to: BUILD_DIR + '/images/favicon-144x144.png' },
                { from: APP_DIR + '/images/favicon-152x152.png', to: BUILD_DIR + '/images/favicon-152x152.png' },
                { from: APP_DIR + '/images/favicon-160x160.png', to: BUILD_DIR + '/images/favicon-160x160.png' },
                { from: APP_DIR + '/images/favicon-180x180.png', to: BUILD_DIR + '/images/favicon-180x180.png' },
                { from: APP_DIR + '/images/favicon-192x192.png', to: BUILD_DIR + '/images/favicon-192x192.png' }
            ]),
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NoEmitOnErrorsPlugin(),

            new BundleAnalyzerPlugin({analyzerMode: 'static'}),
            //new PrintChunksPlugin()

            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                minChunks: function (module) {
                   // this assumes your vendor imports exist in the node_modules directory
                   return module.context && module.context.indexOf('node_modules') !== -1;
                }
            }),

            //CommonChunksPlugin will now extract all the common modules from vendor and main bundles
            new webpack.optimize.CommonsChunkPlugin({
                name: 'manifest' //But since there are no more common modules between them we end up with just the runtime code included in the manifest file
            }),

            new CompressionPlugin({
              asset: "[path].gz[query]",
              algorithm: "gzip",
              test: /\.js$|\.css$|\.html$/,
              threshold: 10240,
              minRatio: 0.8
            })
        ];


        // HERE IS OPTION CONDITION
        // edit .env file change to EnableCircularDependencyPlugin=false will bypass it
        if (process.env.EnableCircularDependencyPlugin=="true") {
            plugins.push(new CircularDependencyPlugin({
                // exclude detection of files based on a RegExp
                exclude: /a\.js|node_modules/,
                // add errors to webpack instead of warnings
                failOnError: true
            }));
        }

        return plugins;
    })(),
    node: {
        net: 'empty',
        dns: 'empty'
    }
};

module.exports = config;

1 个答案:

答案 0 :(得分:1)

经过一夜安眠后,我今天早上找到了解决办法。 发布了Webpack 2.0的解决方案here。 所以我只需要将它改编为Webpack 3.0

只需改变:

presets: [
  'env',
  {
    "modules": false
  },
  'react',
  'stage-2']

为:

presets: [
  ['env',
    {
      "modules": false
    }],
  'react',
  'stage-2']
})

之后,npm能够毫无问题地构建。