繁体   English   中英

webpack 2反应代码拆分

[英]webpack 2 react code splitting

我试图在路线上拆分反应代码,但收到此错误: 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 Router上正确使用了导入,或者问题可能与Django有关。

有人可以帮我吗?

提前致谢。

这可能是在生成的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 = "/"配置。 这应该使脚本路径绝对。

类似的问题是在带有webpack的React-Router中使用嵌套路由的问题。

通常,“ <”上的错误表示它无法解析。 这意味着babel + react配置可能未在文件上运行。 当您查看webpack配置时,babel仅在jsx上运行。 由于您在懒惰的时候没有添加该扩展名,因此它不会通过该加载器运行。 您可以更改正则表达式以通过babel运行所有js文件(不包括node),也可以在导入文件时显式添加.jsx扩展名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM