手順
バージョン違いでうまくいかなかった時に切り分けしやすいように、create-react-appのバージョンを確認しておく。
$ npx create-react-app --version
5.0.0
必要な手順を確認するため、新しいアプリを作成する。
$ npx create-react-app vanilla-extract-app --template typescript
毎回、思うけどcreate-react-appってauditにめっちゃ引っかかる。
$ npm audit report | grep vulnerabilities
30 vulnerabilities (18 moderate, 12 high)
create-react-appV5に対応していないのでforceオプションをつけてcracoを導入する。
試しに使ってみたい段階なので問題ないが、期間を決めてエラーが解消されないなら別の方法を探すのがよさそう。
$ npm install -f @craco/craco --save-dev
公式のインストール方法に従い、package.jsonを修正。
diff --git a/package.json b/package.json
index ec1a771..aa4f47c 100644
--- a/package.json
+++ b/package.json
@@ -12,9 +12,9 @@
"web-vitals": "^2.1.4"
},
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
"eject": "react-scripts eject"
},
"eslintConfig": {
craco.config.jsを作成する。
const { VanillaExtractPlugin } = require('@vanilla-extract/webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
babel: {
plugins: ["@vanilla-extract/babel-plugin"],
},
webpack: {
plugins: {
add: [new VanillaExtractPlugin()]
},
configure: (config) => {
config.module.rules.push({
test: /\.vanilla\.css$/i,
use: [
MiniCssExtractPlugin.loader,
{
loader: require.resolve('css-loader'),
options: {
url: false
}
}
]
})
return config;
},
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
],
},
},
};
順番が前後するが、必要なモジュールを追加する。
$ npm install @vanilla-extract/css @vanilla-extract/babel-plugin @vanilla-extract/webpack-plugin --save-dev
styles.css.tsを作成して、文字色を変える程度のstyleを作成する。
import { style } from '@vanilla-extract/css';
export const SampleStyle = style({
color: 'yellow',
});
動作確認までが目的なので、App.jsを編集してstyles.css.tsで作成したSampleStyleが適用されることを確認する。
--- a/src/App.js
+++ b/src/App.js
@@ -1,12 +1,13 @@
import logo from './logo.svg';
import './App.css';
+import { SampleStyle } from './styles.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
- <p>
+ <p className={SampleStyle}>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
動作確認が終わった時点でのファイル構造はこんな感じ
$ tree -L 1 .
.
├── README.md
├── craco.config.js
├── node_modules
├── package-lock.json
├── package.json
├── public
└── src
$ tree -L 1 ./src
./src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
├── reportWebVitals.js
├── setupTests.js
└── styles.css.ts