1

我正在使用 Webpack、Gulp 和 React 在我的 Jekyll 静态站点中使用 React 应用程序。我在 React 元素上收到了一个意外的令牌错误:

Module parse failed: Unexpected token (8:4)
You may need an appropriate loader to handle this file type.
| window.mount = function(id, type) {
|   render(
|     <App type={type} />,
|     document.getElementById(id)
|   )

我尝试了各种方法和 babel 预设。

webpack.config.js

module.exports = {
  entry: {
    app: './webpack/app.js'
  },
  output: {
    path: __dirname + '/src/_assets/js',
    filename: 'app.js'
  },
  module: {
    rules: [{
      // I've tried node_modules/my-app as well
      include: __dirname + 'node_modules/my-app/src',
      test: /\.(js|jsx)$/,
      use: {
        loader: "babel-loader",
        options: {
          // I've tried several variations of this:
          presets: ["react", "env", "stage-0", "es2015", { targets: { node: true } }],
        }
      }
    }]
  }
};

相关的gulp代码:

const webpack_stream = require('webpack-stream');
const webpack_config = require('./webpack.config.js');

// I have tried gulp-webpack and gulp ( no webpack ) with the babel-loader
gulp.task('app', function () {
  return webpack_stream(webpack_config).pipe(gulp.dest('src/_assets/js/'));
});

任何人都可以看到我遗漏的任何东西,有错误,或者版本/预设有问题吗?

我已经浏览了其他类似的问题和答案,比如这个这个,但没有运气。

编辑1:

如果我将 webpack.config.js 更改为使用 babel-polyfill 并排除而不是包含,我可以克服第一个错误,但我仍然在<Provider>元素上出错。

**webpack.config**

module.exports = {
  entry: './webpack/rfi.js',
  output: {
    path: __dirname + '/src/_assets/js',
    filename: 'rfi.js'
  },
  module: {
    rules: [{
      exclude: /node_modules/,
      test: /\.(js|jsx)$/,
      use: {
        loader: "babel-loader",
        options: {
          presets: ["react", "env", "stage-3", "es2015"],
        }
      }
    }]
  }
};

**App.js**

class Rfi extends Component {
  render() {
    return (
        <Provider store={store}>
          <Form />
        </Provider>
    );
  }
}

**error**

Module parse failed: Unexpected token (36:8)
You may need an appropriate loader to handle this file type.
|
|     return (
|         <Provider store={store}>
|           <Form />
|         </Provider>

是的 Provider 已导入import { Provider } from 'react-redux';

编辑 2(根据评论请求)

出于某种原因,我不再在我的消息中得到很好的跟踪。这是昨天的一个。

在此处输入图像描述

4

1 回答 1

2

其中一种方法是使用babel-polyfill,您可以将其安装为项目依赖项npm install --save babel-polyfill,并在您的内部webpack.config.js将其传递给入口点(您可以相应地修改它):

entry: ["babel-polyfill", "./webpack/app.js"],

编辑 1 个答案

您需要确保您的商店位于层次结构的顶部,例如(app.js)(您可以相应地修改它):

import { render } from "react-dom";

import { Provider } from "react-redux";

render(
    <Provider store={store}>
        <Form />
    </Provider>,
    document.getElementById("app") // Ammend this accordignly
);

您可以在此处阅读有关 babel Polyfill 的更多信息

于 2018-03-13T16:12:06.327 回答