webpack 2反应代码分裂

时间:2017-01-16 13:07:14

标签: django reactjs react-router webpack-2

我正在尝试在路线上拆分反应代码但我收到此错误:Uncaught SyntaxError: Unexpected token <

这是我的webpack代码:

var path = require('path')
var webpack = require('webpack')
var HappyPack = require('happypack')
var BundleTracker = require('webpack-bundle-tracker')
var path = require('path')
var ExtractTextPlugin = require("extract-text-webpack-plugin")
var polyfill = require("babel-polyfill")

function _path(p) {
  return path.join(__dirname, p);
}

module.exports = {

    context: __dirname,
    entry: {
        index: './assets/js/index',
    }, 

    output: {
        path: path.resolve('./assets/bundles/'), 
        filename: '[name]-[hash].js'
    },

    devtool: 'inline-eval-cheap-source-map',

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}), 
        new webpack.ProvidePlugin({ 
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery' 
        }),
        new HappyPack({
            threads: 4,
            loaders: [ 'babel-loader' ],
        }),
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /pt-br/)
    ],

    module: {
        rules: [

             {
                test: /\.css$/,
                include: path.resolve(__dirname, './assets/css/'),
                use: ["style-loader", "css-loader", "resolve-url-loader"]
                // use: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: ["css-loader", "resolve-url-loader"]})
            },

            {
                test: /\.scss$/,
                include: path.resolve(__dirname, './assets/css/'),
                use: ["style-loader", "css-loader", "resolve-url-loader", "sass-loader"]
                // use: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: ["css-loader", "resolve-url-loader", "sass-loader"]})
            },

            {
                test: /\.scss$/,
                include: path.resolve(__dirname, './assets/vendors/'),
                use: ["style-loader", "css-loader", "resolve-url-loader", "sass-loader"]
                // use: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: ["css-loader", "resolve-url-loader", "sass-loader"]})
            },

            {
                test: /\.jsx?$/, 
                include: path.resolve(__dirname, './assets/js/'),
                exclude: /node_modules/, 
                use: [{
                  loader: 'happypack/loader',
                }]
            },
            {
                test: /\.png$/,
                use: { 
                        loader: 'file-loader' ,
                        options: {
                            name: '/static/img/[name].[ext]'
                        }
                    }

            }
        ]
    },

    resolve: {
        extensions: ['.js', '.jsx'],
        modules: [ path.resolve(__dirname, 'node_modules')]
    }   
}

我的babelrc代码:

{
  "presets": [
                ["es2015", {modules: false}],
                "react"
            ]
}

我的路由器:

<Router history={browserHistory}>
        <Route path="login" onEnter={redirectHome} getComponent={(location, cb) => {
              System.import('./components/common/LoginPage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
    <Route path="app" onEnter={requireAuth} getComponent={(location, cb) => {
              System.import('./components/App')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          }>
      <IndexRoute getComponent={(location, cb) => {
              System.import('./components/middle/dashboard/DashboardPage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          }/>
      <Route path="clients">
          <IndexRoute getComponent={(location, cb) => {
              System.import('./components/middle/clients/ClientPage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          <Route path="form/:method(/:clientId)" getComponent={(location, cb) => {
              System.import('./components/middle/clients/ClientForm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          <Route path="detail/:id" getComponent={(location, cb) => {
              System.import('./components/middle/clients/ClientDetail')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          <Route path="attends/:clientId" getComponent={(location, cb) => {
              System.import('./components/middle/attends/ClientAttend')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
      </Route>
      <Route path="contacts">
            <Route path="form/:method/:client(/:contactId)" getComponent={(location, cb) => {
              System.import('./components/middle/contacts/ContactForm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="list/:id" getComponent={(location, cb) => {
              System.import('./components/middle/contacts/ContactPage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="detail/:id/:contactId" getComponent={(location, cb) => {
              System.import('./components/middle/contacts/ContactDetail')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
        </Route>
        <Route path="transmissors">
          <Route path="form/:method/:client(/:transmissorId)" getComponent={(location, cb) => {
              System.import('./components/middle/transmissors/TransmissorForm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          <Route path="list/:id" getComponent={(location, cb) => {
              System.import('./components/middle/transmissors/TransmissorPage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="detail/:client(/:transmissorId)" getComponent={(location, cb) => {
              System.import('./components/middle/transmissors/TransmissorDetail')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
        </Route>
        <Route path="attends">
            <IndexRoute getComponent={(location, cb) => {
              System.import('./components/middle/attends/AttendancePage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="call/:id(/:attend)" getComponent={(location, cb) => {
              System.import('./components/middle/attends/AttendanceDetail')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          </Route>
          <Route path="reports">
            <IndexRoute getComponent={(location, cb) => {
              System.import('./components/middle/reports/ReportPage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="list/alarms/:filter" getComponent={(location, cb) => {
              System.import('./components/middle/reports/ReportAlarm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="list/attendants/:filter" getComponent={(location, cb) => {
              System.import('./components/middle/reports/ReportAttendant')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="list/clients/:filter" getComponent={(location, cb) => {
              System.import('./components/middle/reports/ReportClient')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          </Route>
          <Route path="user/form/:method(/:userId)" getComponent={(location, cb) => {
              System.import('./components/middle/user/UserForm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          <Route path="manage">
            <Route path="phones" getComponent={(location, cb) => {
              System.import('./components/middle/user/UserForm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />     
            <Route path="attend" getComponent={(location, cb) => {
              System.import('./components/middle/manage/ManageAttend')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
            <Route path="alarms" getComponent={(location, cb) => {
              System.import('./components/middle/manage/AlarmManagement')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />      
          </Route>
          <Route path="events">
            <Route path="detail/:id" getComponent={(location, cb) => {
              System.import('./components/middle/events/EventsPage')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          </Route>
          <Route path="alarms">
            <Route path="form/:method(/:alarmId)" getComponent={(location, cb) => {
              System.import('./components/middle/manage/AlarmForm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          </Route>
          <Route path="phones">
            <Route path="form/:method(/:phoneId)" getComponent={(location, cb) => {
              System.import('./components/middle/manage/PhoneForm')
                .then(loadRoute(cb))
                .catch(errorLoading);
            }
          } />
          </Route>
    </Route>
    <Route path="*" onEnter={redirect}/>
    </Router>

我在后端使用django,以及不支持webpack代码拆分的webpack-bundle-tracker。

所以我创建了一个问题并为此做了一个解决方案(或解决方法): https://github.com/owais/webpack-bundle-tracker/issues/19

我的index.html是:

{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no" />
    <title>title</title>
    <link rel="icon" type="image/png" sizes="32x32" href="static/img/favicon-32x32.png">
    {% render_bundle 'index' 'css' %}
  </head>

  <body>
    <div id ="app" class="app"></div>
    <audio id="audio_sip" autoplay="autoplay"></audio>
    {% render_bundle 'index' 'js' %}
    {% render_bundle 'split' 'js' %}
  </body>
</html>

所以我不知道我是否在反应路由器上正确使用导入,或者问题可能与django有关。

有人能帮我吗?

提前致谢。

2 个答案:

答案 0 :(得分:2)

这可能是生成的index.html中自动插入脚本引用中没有绝对路径的副作用。例如。如果生成的脚本语句是<script src="./index.js"></script>,那么当您在子路径上说/contacts并且刷新时,浏览器将要求/contacts/index.js。如果您的服务器改为发回index.html,那么浏览器将无法尝试将html解析为JS并且会抱怨无效的<字符。

要验证这一点,请对index.html文件中的绝对引用进行硬编码,如下所示 - <script src="/index.js"></script>,然后刷新以检查问题是否仍然存在。

如果事实确实如此,请阅读有关如何修改index.html模板以插入绝对路径的信息,因为我担心我不熟悉您使用的模板语法。

应该运行的一个修复是在webpack.config.js文件中进行output.publicPath = "/"配置。这应该使脚本路径绝对。

类似的问题是Issue using nested routes in React-Router with webpack

答案 1 :(得分:0)

通常错误在&#34;&lt;&#34;是一个无法解析的指标。这意味着babel + react配置可能不会在文件上运行。当你查看你的webpack配置时,babel只能在jsx上运行。由于您懒得加入时不会添加该扩展名,因此它不会通过该加载程序运行。您可以更改正则表达式以通过babel运行所有js文件,不包括节点,也可以在导入文件时显式添加.jsx扩展名。