代码之家  ›  专栏  ›  技术社区  ›  Sourabh Banka

“babel plugin react intl”没有按预期工作

  •  2
  • Sourabh Banka  · 技术社区  · 7 年前

    create-react-app 命令。现在我想用印地语和英语提供我的网站。 yahoo/react-intl . 我还安装了babel插件react intl插件。还添加了.babelrc文件。

    我的 .babelrc

    {
    "presets": ["es2015", "react"],
    "plugins": [
      [
        "react-intl",
        {
          "messagesDir": "./build/messages/"
        }
      ]
    ]
    }
    

    但是我没有从js文件中提取消息到 ./build/messages/

    我不知道我在哪里犯了错误。

    我的index.js是:

    import React from "react";
    import ReactDOM from "react-dom";
    import { IntlProvider, addLocaleData } from "react-intl";
    import hi from "react-intl/locale-data/hi";
    import en from "react-intl/locale-data/en";
    
    import registerServiceWorker from "./registerServiceWorker";
    import Hello from "./components/Hello";
    
    addLocaleData([...en, ...hi]);
    
    ReactDOM.render(
      <IntlProvider locale="hi" messages={/*comming soon*/}>
        <Hello />
      </IntlProvider>,
      document.getElementById("root")
    );
    registerServiceWorker();
    

    我的敌人 Hello.js

    import React, { Component } from "react";
    import { FormattedMessage } from "react-intl";
    
    class Hello extends Component {
      render() {
        return (
          <div>
            <h1>
              <FormattedMessage id="Hello.heading" defaultMessage="Hello world" />
            </h1>
            <p>
              <FormattedMessage
                id="Hello.paragraph"
                defaultMessage="This is my world"
              />
            </p>
          </div>
        );
      }
    }
    
    export default Hello;
    

    我的 package.json

    {
    "name": "i18n-myexamplae",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
      "react": "^16.4.2",
      "react-dom": "^16.4.2",
      "react-intl": "^2.4.0",
      "react-scripts": "1.1.4"
    },
    "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build",
      "test": "react-scripts test --env=jsdom",
      "eject": "react-scripts eject"
    },
    "devDependencies": {
      "babel-plugin-react-intl": "^2.4.0"
    }
    }
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   TomáÅ¡ Ehrlich    7 年前

    这是因为 react-scripts .babelrc . 你要么需要弹出,因为这样你就可以编辑 巴贝尔 或者你需要手动运行babel。

    ./node_modules/.bin/babel src --out-dir lib 忽略/删除 --out-dir . 你这样做只是为了提取信息。另外,要使构建一致,请替换 es2018 react 预设 react-app 预设,即 create-react-app

    注: 使用时 预设您实际上需要运行 NODE_ENV=development ./node_modules/.bin/babel src --out-dir lib ,因为 反应脚本 package.json 让事情更容易。

    "scripts": {
      "extract": "NODE_ENV=development babel src --out-dir lib",
      ...
    },
    

    我在写的i18n图书馆也遇到过类似的问题, lingui . lingui extract 创建react应用程序 如果是的话,它使用 react应用程序