由于“找不到模块'环境'。TS2307”,craco导致纱线构建失败

时间:2020-01-19 11:29:15

标签: reactjs typescript create-react-app environment craco

我在official READMEmedium article "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.ts

来配置craco
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)
      }
    },
  };
};

并使用cracoyarn add @craco/craco --devcross-env安装到yarn add cross-env

现在,如果要使用环境引用来访问environment.someKey中的App,则需要在import environment from "environment";中添加src/App.tsx,但这会导致{{1 }}和yarn build由于以下原因而失败

yarn start

如何使用此创建的设置?

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

1 个答案:

答案 0 :(得分: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"
  },