Ошибка сборки при использовании производственной сборки веб-пакета - PullRequest
0 голосов
/ 03 мая 2018

Я получаю сбой сборки модуля: SyntaxError: Неожиданная ошибка токена. Я получаю эту ошибку при создании производственной сборки, прежде чем применить конфигурацию производственной сборки Webpack, такой же код работал ранее при использовании сборки разработки. Можете ли вы предложить мне, что я делаю неправильно в webpack.config.js Вот ошибка

ERROR in ./src/index.jsx
Module build failed: SyntaxError: Unexpected token (10:4)
client    |
client    |    8 |
client    |    9 | const App = () => (
client    | > 10 |     <Provider store={store}>
client    |      |     ^
client    |   11 |         <AppRoute/>
client    |   12 |     </Provider>
client    |   13 | );

Вот мой код файла webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');

const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname, 'src');
const buildPath = path.join(__dirname, 'dist');


module.exports = {
    devtool: 'source-map',
    entry: {
        app: path.resolve(sourcePath, 'index.jsx')
    },
    output: {
         path: path.join(__dirname, 'dist'),
         filename: '[name].[chunkhash].js',
         publicPath: '/'
    },
    resolve: {
         extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
         modules: [
             sourcePath,
             path.resolve(__dirname, 'node_modules')
         ]
    },
    plugins: [
        new webpack.DefinePlugin({
             'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
             name: 'vendor',
             filename: 'vendor.[chunkhash].js',
             minChunks (module) {
                 return module.context && module.context.indexOf('node_modules') >= 0;
             }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                screw_ie8: true,
                conditionals: true,
                unused: true,
                comparisons: true,
                sequences: true,
                dead_code: true,
                evaluate: true,
                if_return: true,
                join_vars: true
            },
            output: {
                comments: false
            }
        }),
        new webpack.LoaderOptionsPlugin({
            options: {
                postcss: [
                    autoprefixer({
                        browsers: [
                          'last 3 version',
                          'ie >= 10'
                        ]
                    })
                ],
                context: staticSourcePath
            }
        }),
        new webpack.HashedModuleIdsPlugin(),
        new HtmlWebpackPlugin({
            template: path.join(sourcePath, 'index.html'),
            path: buildPath,
            filename: 'index.html',
            minify: {
                 collapseWhitespace: true,
                 collapseInlineTagWhitespace: true,
                 removeComments: true,
                 removeRedundantAttributes: true
            }
        }),
        new PreloadWebpackPlugin({
            rel: 'preload',
            as: 'script',
            include: 'allChunks',
            fileBlacklist: [/\.(css|map)$/, /base?.+/]
        }),
        new ScriptExtHtmlWebpackPlugin({
            defaultAttribute: 'defer'
        }),
        new ExtractTextPlugin({
            filename: '[name].[contenthash].css',
            allChunks: true
        }),
        new CompressionPlugin({
            asset: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
            threshold: 10240,
            minRatio: 0.8
        })
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: [
                   'babel-loader'
                ]
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        { loader: 'css-loader', options: { minimize: true } },
                        'postcss-loader',
                        'sass-loader'
                    ]
                })
            },
            {
                test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
                use: 'file-loader?name=assets/[name]-[hash].[ext]'
            },
            {
                test: /\.(png|gif|jpg|svg)$/,
                use: [
                     'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
                ],
                include: staticSourcePath
            }
       ]
   }
};

А вот мой код index.jsx.

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './_helpers';
import  AppRoute  from './pages/approute';

import 'react-table/react-table.css';

const App = () => (
    <Provider store={store}>
        <AppRoute/>
    </Provider>
);

ReactDOM.render(<App />, document.getElementById('app'));

Ответы [ 2 ]

0 голосов
/ 03 мая 2018

Окончательное обновление в webpack.config.js

test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
     loader: 'babel-loader',
     options: {
         cacheDirectory: true,
         presets: ['react', 'es2015', 'stage-3']
     }
}
0 голосов
/ 03 мая 2018

Как указано в комментарии, в конфигурации babel должно быть что-то, что webpack не может передать синтаксис JSX.

Проверьте, установлено ли и включено ли babel-preset-response :

"presets": [
   "react"
],

Little nitpick - используйте кэширование для более быстрых инкрементных сборок:

{
   test: /\.jsx?$/,
   exclude: /node_modules/,
   use: {
     loader: 'babel-loader',
     options: {
       cacheDirectory: true,
     },
   },
},
...