无论我尝试什么,Webpack都不会解析JSX

时间:2016-09-05 06:09:06

标签: reactjs webpack jsx

已经过了几天......

尝试使用Webpack对React模块进行延迟加载,首先在服务器上呈现app-shell,然后在客户端上注入Router。使用gulp时编译很好,但是使用Webpack,我得到了臭名昭着的声明:

在../server/components/routes/AppRouter.jsx中出现错误 模块解析失败:/web/sites/react-lazy/server/components/routes/AppRouter.jsx意外令牌(11:6) 您可能需要适当的加载程序来处理此文件类型。

AppRouter.jsx:

import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import routes from './AppRoute.jsx';
import createMemoryHistory from 'history/lib/createMemoryHistory';

if (typeof require.ensure !== 'function') require.ensure = (d, c) => c(require)

export default class AppRouter extends React.Component {
  render() {
    return (
      <Router routes={routes} history={createMemoryHistory()} /> // < -- errors here
    ); 
  }
}

我的webpack.config.js:

var path = require('path')

module.exports = {
  context: __dirname + "/src",
  entry: './js/app.es6.js',
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [ 
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: path.resolve(__dirname, 'src/js'),
        exclude: /(node_modules)/,
        query: {
          presets: ["es2015", "stage-0", "react"],
        }
      }
    ]
  },

  output: {
    path: __dirname + '/build',
    publicPath: '/build',
    filename: 'app.js',
    chunkFilename: '[id].chunk.js',
  }
}

我的目录结构:

  /
    webpack.config.js
    .babelrc
    /src
       /js
          app.es6.js
          .babelrc // <-- also put a .babelrc here in case 

我的package.json:

  "devDependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.14.0",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.5.0",
    "babel-register": "^6.14.0", 
    "webpack": "^1.13.2",
    ...
 }

我试过了:

  • 将.babelrc文件复制到主目录和入口点目录中,不确定哪个是必需的。
  • 登记 babel-register:在app.es6.js:

    require('babel-register')({
      presets: [ 'es2015', 'stage-0', 'react' ]
    });
    
  • 使用&#39;运行webpack - config webpack.config.js&#39;参数
  • 如果我将babel,babel-core和babel-loader版本降级为5. *(从6. *开始),则会出现另外的错误:

    ERROR in ./js/app.es6.js
    Module build failed: ReferenceError: [BABEL] /web/sites/react-lazy/src/js/app.es6.js: Unknown option: direct.presets
    

我应该说,我对React和webpack相当新。有人知道其他任何技巧吗?

解决方案:

  • webpack config&#39; include&#39;属性必须包含您需要通过加载器的所有目录

1 个答案:

答案 0 :(得分:2)

您的输入文件使用位于此处的组件:

/web/sites/react-lazy/server/components/

但是,您的include配置只允许将/web/sites/react-lazy/src/js/以下的文件传递给加载程序(include表示:“应该传递给此加载程序的所有文件必须位于此目录“)。

因此,要么删除include配置,要么使其成为一个数组,其中还包含可以找到.jsx文件的其他位置。