【问题标题】:Use alt with react in ES6在 ES6 中使用 alt 和 react
【发布时间】:2020-05-01 14:18:16
【问题描述】:

我正在尝试将 alt 与 React 一起使用并以 ES6 样式编写 Action:

import alt from '../alt';

class LoginActions {
  login() {
    alert('oi');
  }
}

export default alt.createActions(LoginActions);

我的 .babelrc 正在使用类转换插件:

// without options
{
    "plugins": ["transform-class-properties"]
}

我的 package.json 配置了 babel 和 webpack

{
  "name": "npm-yarn-babel-webpack",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "babel-core": "6",
    "babel-loader": "7",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^1.0.1",
    "node-sass": "^4.10.0",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.1",
    "webpack": "^4.25.1",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.10"
  },
  "dependencies": {
    "alt": "^0.18.6",
    "react": "^16.6.3",
    "react-dom": "^16.6.3"
  },
  "scripts": {
    "build": "webpack -p",
    "dev": "webpack-dev-server --hot --inline"
  }

我有一个组件 Hello World:

import React, { Component } from 'react';

import LoginActions from './LoginActions';

export class HelloWorld extends Component {


    render() {
        return (
            <div className="hello-world">
                <h1>Hello World</h1>
            </div>
        );
    }
}
export default HelloWorld;

我正在运行:

yarn run dev

如果我不导入 LoginActions,它会起作用,当我导入时,它会编译,但它不起作用。

如果我使用 react-scripts 运行,它会显示 alt 可以理解 ES6 类定义的错误。

我做错了什么?

【问题讨论】:

  • 你的 package.json 中有 alt,所以你可以这样做:import alt from 'alt';
  • 我需要在调用它之前实例化 alt,我在 alt.js 文件中进行并导入 alt 实例化
  • 你收到错误了吗?
  • 你需要把所有的代码都放在这里。如果你也添加codsandbox.io会更好

标签: reactjs webpack babeljs alt


【解决方案1】:

您的 babel-loader 仅配置为 .jsx 文件。您还需要为 alt.js 所在的 .js 文件配置它。为此,请使用正则表达式 /\.jsx?/

   {
         test: /\.jsx?/,
         use: {
            loader: 'babel-loader',
            options: { presets: ['react', 'es2015'] }
         }
     },

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 2016-11-11
    • 2017-12-01
    • 2019-04-24
    • 2015-05-19
    • 1970-01-01
    • 2017-07-02
    • 2015-12-02
    • 2015-10-28
    相关资源
    最近更新 更多