苦苦挣扎升级到WebPack 2

时间:2017-05-16 20:05:24

标签: javascript node.js reactjs webpack webpack-2

我正在尝试从1迁移到Webpack 2并且收到了很多错误。我设法摆脱了一些错误,但仍然收到以下内容:

$ node scripts / start.js (node:42015)UnhandledPromiseRejectionWarning:未处理的promise promise(拒绝ID:1):WebpackOptionsValidationError:无效的配置对象。 Webpack已使用与API架构不匹配的配置对象进行初始化。

  • configuration.resolve有一个未知属性'fallback'。这些属性是有效的: object {alias?,aliasFields?,cachePredicate?,descriptionFiles?,enforceExtension?,enforceModuleExtension?,extensions?,fileSystem?,mainFields?,mainFiles?,moduleExtensions?,modules?,plugins?,resolver?,symlinks?,unsafeCache?, useSyncFileSystemCalls? } (节点:42015)

弃用警告:不推荐使用未处理的拒绝承诺。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程。

我的webpack配置位于

之下
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ManifestPlugin = require('webpack-manifest-plugin');
var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
var url = require('url');
var paths = require('./paths');
var getClientEnvironment = require('./env');


function ensureSlash(path, needsSlash) {
    var hasSlash = path.endsWith('/');
    if (hasSlash && !needsSlash) {
        return path.substr(path, path.length - 1);
    } else if (!hasSlash && needsSlash) {
        return path + '/';
    } else {
        return path;
    }
}


// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
var homepagePath = require(paths.appPackageJson).homepage;
var homepagePathname = homepagePath ? url.parse(homepagePath).pathname : 

%PUBLIC_PATH%xyz.
var publicUrl = ensureSlash(homepagePathname, false);

var env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env['process.env'].NODE_ENV !== '"production"') {
    throw new Error('Production builds must have NODE_ENV=production.');
}

module.exports = {

    bail: true,

    entry: [
        require.resolve('./polyfills'),
        paths.appIndexJs
    ],
    output: {
        // The build folder.
        path: paths.appBuild,
        // Generated JS file names (with nested folders).
        // There will be one main bundle, and one file per asynchronous chunk.
        // We don't currently advertise code splitting but Webpack supports it.
        filename: 'assets/static/js/[name].js',
        chunkFilename: 'assets/static/js/[name].chunk.js',
        // We inferred the "public path" (such as / or /my-project) from homepage.
        publicPath: publicPath
    },
    resolve: {

       extensions: ['.js', '.json', '.jsx'],
        alias: {
            // Support React Native Web
            // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
            'react-native': 'react-native-web'
        }
    },

    module: {

        rules: [

            {
                test: /\.(js|jsx)$/,
                loader: 'eslint',
                include: paths.appSrc,
                enforce: 'pre'
            },
            {
                exclude: [
                    /\.html$/,
                    /\.(js|jsx)$/,
                    /\.css$/,
                    /\.json$/,
                    /\.svg$/
                ],
                loader: 'url',
                options: {
                    limit: 10000,
                    name: 'static/media/[name].[hash:8].[ext]'
                }
            },
            // Process JS with Babel.
            {
                test: /\.(js|jsx)$/,
                include: paths.appSrc,
                loader: 'babel',

            },

            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract('style', 'css?importLoaders=1!postcss')
                // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
            },
            // JSON is not enabled by default in Webpack but both Node and Browserify
            // allow it implicitly so we also enable it.
            {
                test: /\.json$/,
                loader: 'json'
            },
            // "file" loader for svg
            {
                test: /\.svg$/,
                loader: 'file',
                options: {
                    name: 'static/media/[name].[hash:8].[ext]'
                }
            }
        ]
    },


    plugins: [
        // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.:
        // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
        // In production, it will be an empty string unless you specify "homepage"
        // in `package.json`, in which case it will be the pathname of that URL.
        new InterpolateHtmlPlugin({
            PUBLIC_URL: publicUrl
        }),
        // Generates an `index.html` file with the <script> injected.
        new HtmlWebpackPlugin({
            inject: true,
            template: paths.appHtml,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true
            }
        }),
        // Makes some environment variables available to the JS code, for example:
        // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
        // It is absolutely essential that NODE_ENV was set to production here.
        // Otherwise React will be compiled in the very slow development mode.
        new webpack.DefinePlugin(env),
        // This helps ensure the builds are consistent if source hasn't changed:
        new webpack.optimize.OccurrenceOrderPlugin(),
        // Try to dedupe duplicated modules, if any:
        new webpack.optimize.DedupePlugin(),
        // Minify the code.
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                screw_ie8: true, // React doesn't support IE8
                warnings: false
            },
            mangle: {
                screw_ie8: true
            },
            output: {
                comments: false,
                screw_ie8: true
            }
        }),
        // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
        new ExtractTextPlugin('assets/static/css/[name].css'),
        // Generate a manifest file which contains a mapping of all asset filenames
        // to their corresponding output file so that tools can pick it up without
        // having to parse `index.html`.
        new ManifestPlugin({
            fileName: 'asset-manifest.json'
        })
    ],
    // Some libraries import Node modules but don't use them in the browser.
    // Tell Webpack to provide empty mocks for them so importing them works.
    node: {
        fs: 'empty',
        net: 'empty',
        tls: 'empty'
    }
};

我的start.js在这里https://pastebin.com/ENRYKUgL

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

fallbackExtractTextPlugin的一个选项,可能尝试使用新的use: { //.. }表示法而不是查询字符串表示法进行定义。这可能不完美,但应该让你开始...

{
  test: /\.css$/,
  loader: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [
      { loader: 'css-loader', options: {importLoaders: 1}},
      { loader: 'postcss-loader' }
    ]
  })
}

在旁注中,您不应该在Webpack 2中需要OccurrenceOrderPlugin或DedupePlugin,因为它们默认包含在内