使用webpack生成版本时构建失败

时间:2018-05-03 09:57:07

标签: reactjs webpack webpack-dev-server webpack-style-loader html-webpack-plugin

我收到模块构建失败: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 :(得分:1)

正如评论中指出的那样,必须有一些babel配置,webpack无法转换JSX语法。

检查您是否已安装babel-preset-react并开启:

"presets": [
   "react"
],

Little nitpick - 使用缓存来实现更快的增量构建:

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

答案 1 :(得分:0)

webpack.config.js中的最终更新

test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
     loader: 'babel-loader',
     options: {
         cacheDirectory: true,
         presets: ['react', 'es2015', 'stage-3']
     }
}