【问题标题】:webpack 2 react code splittingwebpack 2 反应代码拆分
【发布时间】:2017-05-31 08:03:32
【问题描述】:

我正在尝试在路由处拆分反应代码,但收到此错误: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>

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

谁能帮帮我?

提前致谢。

【问题讨论】:

  • 如果你说的是应用路由,是}>
  • 我没有看到它在某处有一个结束标签。
  • - 用于应用程序 - 应用程序有很多孩子

标签: django reactjs react-router webpack-2


【解决方案1】:

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

为了验证这一点,在 index.html 文件中硬编码绝对引用,就像这样 - &lt;script src="/index.js"&gt;&lt;/script&gt;,然后刷新以检查问题是否仍然存在。

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

一个应该有效的修复方法是在您的 webpack.config.js 文件中添加 output.publicPath = "/" 配置。这应该使脚本路径成为绝对路径。

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

【讨论】:

  • 谢谢你!我将 publicPath 设置为“/static/bundle/”文件所在的路径
【解决方案2】:

通常,“

【讨论】:

  • 我做了两件事:将正则表达式更改为测试:/\.(js|jsx)$/,并在导入文件中添加 .jsx。我仍然有错误,但我的应用程序不再崩溃
  • 同理:Uncaught SyntaxError: Unexpected token
猜你喜欢
  • 2023-03-12
  • 2017-09-30
  • 2016-06-01
  • 1970-01-01
  • 2018-06-21
  • 1970-01-01
  • 2017-07-16
  • 2019-08-19
  • 1970-01-01
相关资源
最近更新 更多