Set up a React website built with webpack
Setup
- Initialize a package.json
npm init
- Install React, Babel, Webpack
yarn add react react-dom babel-loader @babel/core @babel/preset-env @babel/preset-react html-loader html-webpack-plugin webpack webpack-dev-server webpack-cli
- Create
webpack.config.js
at the root of the project
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules\/(?!()\/).*/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"],
},
},
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
},
],
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html",
}),
],
devServer: {
historyApiFallback: true,
contentBase: "./",
hot: true,
},
};
- Create a public/index.html, public/index.js, public/App.js
<!DOCTYPE html>
<html>
<head>
<title>React Native Web Storybook</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("app"));
import React from "react";
export default class App extends React.Component {
render() {
return <div>Hello world</div>;
}
}
Run the website
- Fix “scripts’ in package.json
"scripts": {
"build": "webpack --mode production",
"start": "webpack-dev-server --config ./webpack.config.js --mode development",
},
Setup storybook
Setup
- Install storybook package
yarn add @storybook/react
- Edit scripts in package.json
"scripts": {
"build": "webpack --mode production",
"start": "webpack-dev-server --config ./webpack.config.js --mode development",
"storybook": "start-storybook"
},
- Create .storybook/main.js at the project root
module.exports = {
stories: ["../src/**/*.stories.[tj]s"],
};
Test
- Create src/index.stories.js
import React from "react";
export default { title: "Hello World" };
export const withText = () => <div>Hello World</div>;
Setup React Native Web for React website
yarn add react-native-web
- Add the following configure to “webpack.config.js”
plugins: [...],
resolve: {
alias: {
"react-native$": "react-native-web",
},
},
devServer: {...}
- You can use React Native for the website, edit src/App.js
import React from "react";
import { Text } from "react-native";
export default class App extends React.Component {
render() {
return <Text>Hello world</Text>;
}
}
- Run yarn start to test if the website works well
Setup React Native Web for Storybook
- Create .storybook/webpack.config.js
module.exports = {
resolve: {
alias: {
"react-native$": "react-native-web"
}
}
};
- You can now use React Native for the website, edit src/index.stories.js
import React from "react";
import { Text } from "react-native";
export default { title: "Hello World" };
export const reactNative = () => <Text>React Native Web is Awesome!</Text>;
Leave a Reply