0

我按照官方 README和中篇文章“My Awesome Custom React Environment Variables Setup”安装并配置了 craco 。我做了

  • sudo yarn global upgrade create-react-app
  • create-react-app craco-getting-started
  • yarn add react-scripts typescript @types/react @types/react-dom

并创建了必要的文件

public/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Craco getting started</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

src/App.tsx

import React from "react"

class App extends React.Component {

  render() {
    return <div>Hello world!</div>
  }
}

export { App };

src/index.tsx

import React from "react";
import ReactDOM from "react-dom";
import { App } from "./App";

ReactDOM.render(
  <App/>,
  document.getElementById("root")
);

并添加

"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build"
}

package.json.

到目前为止,样板。yarn start该应用程序以“Hello world!”开头并显示。

现在,我通过创建来配置src/environments/development.tscraco

export default {
  isProduction: false,
  name: "development"
};

src/environments/production.ts

export default {
  isProduction: true,
  name: "production"
};

以及craco.config.js内容

const path = require('path');

module.exports = function({ env, paths }) {
  return {
    webpack: {
      alias: {
        environment: path.join(__dirname, 'src', 'environments', process.env.CLIENT_ENV)
      }
    },
  };
};

craco使用yarn add @craco/craco --dev和安装。cross-envyarn add cross-env

现在,如果我想使用环境引用来访问environment.someKey,例如App我需要添加import environment from "environment";in src/App.tsx,但这会导致yarn build并且yarn start由于以下原因而失败

> yarn build
yarn run v1.21.1
$ cross-env CLIENT_ENV=production craco build
Creating an optimized production build...
Failed to compile.

/mnt/data/home/examples/craco/craco-getting-started/src/App.tsx
TypeScript error in /mnt/data/home/examples/craco/craco-getting-started/src/App.tsx(2,25):
Cannot find module 'environment'.  TS2307

    1 | import React from "react"
  > 2 | import environment from "environment";
      |                         ^
    3 | 
    4 | class App extends React.Component {
    5 | 


error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

如何使用这个创建的设置?

我在https://gitlab.com/krichter-sscce/craco-getting-started提供了一个 SSCCE,其中不包含其他信息,但可以更轻松地重现问题。

4

1 回答 1

0

添加脚本后@craco/craco需要package.json更新为

 "scripts": {
    "start": "CLIENT_ENV=development craco start",
    "build": "CLIENT_ENV=production craco build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
于 2020-01-22T20:21:22.957 回答