我按照官方 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.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)
}
},
};
};
并craco
使用yarn add @craco/craco --dev
和安装。cross-env
yarn 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,其中不包含其他信息,但可以更轻松地重现问题。