背景
reactを勉強して3ヶ月目にして「sassを使ってみよう!」思っていざ導入しようと思ったが、webpack周辺の知識がなさすぎて中断してしまいました。(create-react-appばっかり使ってるせいかな(⦿_⦿))
必要なモジュールのインストール
mkdir react-app ; cd react-app
yarn init -y
yarn add webpack webpack-cli --dev
yarn add babel-core babel-loader babel-preset-env --dev
yarn add react react-dom babel-preset-react --dev
yarn add html-webpack-plugin html-loader --dev
yarn add webpack-dev-server --dev
yarn add sass-loader node-sass style-loader css-loader url-loader --dev
webpack-cliはwebpack4から追加されたらしい
ファイル構成
.
├── dist
│ ├── index.html
│ └── main.js
├── package.json
├── src
│ ├── App.js
│ ├── index.html
│ ├── index.js
│ └── style.scss
├── webpack.config.js
└── yarn.lock
- nodo_modulesディレクトリがあります。
.babelrc
{
"presets": ["env", "react"]
}
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MODE = 'development';
module.exports = {
mode: MODE,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.scss/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false,
importLoaders: 2
},
},
{
loader: 'sass-loader',
}
],
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
src/App.js
import React from "react";
import ReactDOM from "react-dom";
const App = () => {
return (
<div className="test">
</div>
);
};
export default App;
ReactDOM.render(<App />,
document.getElementById("app"));
src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>webpack 4 quickstart</title>
</head>
<body>
<div id="app">
</div>
</body>
</html>
src/index.js
import App from "./App";
import './style.scss';
src/style.scss
body {
background-color: black;
}
最後にpackage.jsonの設定を行います。
{
"name": "reactapptest",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "./node_modules/.bin/webpack-dev-server --mode development --open",
"build": "./node_modules/.bin/webpack"
},
"dependencies": {
"webpack": "^4.2.0",
"webpack-cli": "^2.0.13"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.1.0",
"node-sass": "^4.7.2",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"sass-loader": "^6.0.7",
"style-loader": "^0.20.3",
"url-loader": "^1.0.1",
"webpack-dev-server": "^3.1.1"
}
}
以下のコマンドを打つと真っ黒な画面が出るはずです。
yarn start
参照
[https://ics.media/entry/17376:title]
[https://www.valentinog.com/blog/webpack-4-tutorial/#webpack_4_setting_up_webpack_4_with_React:title]