preface

Example 1: When using React, we use create-react-app to download a react template and start implementing various functions in it.

Case 2: A few months ago, I came across the official website of Feibing. After browsing it, I thought it was good and downloaded several templates from it.

Then we might wonder about two things:

  • How is this template constructed from an empty directory
  • Once the template is set up, how do you define command line downloads

This article will cover these two topics based on one of my own ideas, the React template style.

First, start building

1.1 directory

├ ─ the build/configuration/webpack │ ├ ─ webpack. Base. The js / / webpack Shared configuration │ ├ ─ webpack. Dev. Js / / webpack development environment configuration │ └ ─ webpack. Prod. Js / / ├─ ├─ SRC // project │ ├─ common // │ ├─ favicon // ├─ SRC // project │ ├─ common // │ ├─ favicon // ├─ SRC // ├─ common // │ ├─ Compoents // Self-wrapped component │ ├─ Pages │ ├─ index.js │ ├─ app.css │ ├─ logo.svg / / home page logo │ └ ─ App. JSX ├ ─. Babelrc / / Babel configuration file ├ ─. Browerslistrc / / configuration browser compatibility range ├ ─. Gitignore / / ignore the upload file ├ ─ Package. json ├─ Readme. md //Copy the code

1.2 the initialization

First, we will create an empty directory, and then initialize the project NPM init -y. After executing the command, we will see a package.json file in the directory.

1.3 configuration package. Json

We know that the commands for both the startup and packaging of the project are self-defined from the package.json file. In the created template, there are the start command to start react and the build command to package the React project. Currently, we only configure these two commands, the package command in the development environment, and the start service command in the production environment.

Go to scripts in pakage.json and configure it like this

"scripts": {
    "start": "webpack-dev-server --env.development --config ./build/webpack.base.js", // The development environment starts the service,"dev":"webpack --env.development --config ./build/webpack.base.js"// The development environment packages the code"build": "webpack --env.production --config ./build/webpack.base.js"// The production environment packages the code"build:server": "webpack-dev-server --env.production --config ./build/webpack.base.js"// Production environment start service},Copy the code

Now that we’ve done the basic configuration, we’re left wondering: Is there a problem with setting environment variables differently on different platforms (Mac and Windows)? Based on this problem, we found the cross-env plug-in, so how can we improve the scripts configured above?

"scripts": {
    "start": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.base.js"."dev":"cross-env NODE_ENV=development webpack --config ./build/webpack.base.js"."build": "cross-env NODE_ENV=production webpack --config ./build/webpack.base.js"."build:server": "cross-env NODE_ENV=production webpack-dev-server --config ./build/webpack.base.js"
  },
Copy the code

With that configured, the next step is to configure webPack

1.4 configuration webpack

1.4.1 webpack. Base. Js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const dev = require('./webpack.dev');
const prod = require('./webpack.prod');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const isDev = process.env.NODE_ENV === 'development';

const base = {
    entry: path.resolve(__dirname, '.. /src/index.js'), // entry module: {rules: [{// handle.js,.jsxtest: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: 'babel-loader'}, {// Processing of.csstest: / \. CSS $/, use: [! IsDev && MiniCssExtractPlugin. Loader, / / production environment style out isDev &&'style-loader',
                {
                    loader: 'css-loader', options: {importLoaders: 1 // Import the file to invoke the following loader processing}}, {// intelligent add style prefix loader:"postcss-loader",
                    options:{
                        plugins:[require('autoprefixer')]
                    }
                },
            ].filter(Boolean)
        }, {
            test: / \. SCSS $/, / / CSS preprocessor SCSS processing use: [! IsDev && MiniCssExtractPlugin. Loader, / / production environment out of style isDev &&'style-loader'."css-loader"."sass-loader"
            ].filter(Boolean)
        }, {
            test: /\. Less $/, // CSS preprocessor less processing use:"less-loader"}, {test: /\. Stylus $/, // CSS"stylus-loader"}, {test: /\.(jpe? G | PNG | SVG | GIF) $/, / / handling of image loader:"file-loader",
            options: {
                name: "image/[contentHash].[ext]"}, {},test: / \. (woff | the vera.ttf | eot | otf | ico) $/, / / handling of the fonts icon loader:"file-loader",
            options: {
                name: "image/[name].[ext]"},}, output: {// export filename:'scripts/[name].bundle.js',
        path: path.resolve(__dirname, '.. /dist'}, resolve: {// Add extensions to js and JSX files.'.js'.'.jsx'}, plugins: [! IsDev && new MiniCssExtractPlugin({// CSS style extract filename:'css/[name].[contentHash].css'}), new HtmlWebpackPlugin({// config entry HTML filename:'index.html',
            template: path.resolve(__dirname, '.. /public/index.html'),
            hash: true,
            inject: true,
            favicon: path.resolve(__dirname, '.. /public/favicon.ico'), minify: ! isDev && { removeAttributeQuotes:trueCollapseWhitespace: // collapse attributetrue, / / HTML file fold into a line}}), new webpack. HotModuleReplacementPlugin (),]. Filter (Boolean), devServer: {/ hot/configuration service:true// Compress: // compress:true// Increase page return speed open:trueContentBase: path.resolve(__dirname,'.. /dist'}} module.exports = () => {// Merge webPack according to environmentif (isDev) {
        return merge(base, dev);
    } else {
        returnmerge(base, prod); }}Copy the code

1.4.2 webpack. Dev. Js

module.exports = {
    mode: 'development',}Copy the code

1.4.3 webpack. Prod. Js

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    mode: 'production', plugins: [new CleanWebpackPlugin(), // Clean up dist directory new UglifyJsPlugin({// Automatically remove debugger, console, uglifyOptions after packing: { compress: { drop_debugger:true,               
                    drop_console: true,
                    pure_funcs: ['console.log'.'debugger']
                }
            },
            parallel: true})],}Copy the code

1.5 Viewing The Effect

We can optimize our Webpack configuration

Configuration optimization for WebPack will be covered in a separate article

Customize commands to download your own template

Use the following commands to download a vue/react template: vue/react/create-react-app/create-cli/create-react-app

My cli is called react-demo-cli on NPM, and the command to download the template is create-react-cli download

NPM install react-demo-cli -g create-react-cli download NPM install react-demo-cli -g create-react-cli download

The effect is wonderful

The last

The core of this article is simply two

  • configurationwebpack
  • Build your owncliOnce those two things are settled, the problem won’t be difficult

How to build your React framework from scratch? Create-react-app doesn’t work as well. So, I’m constantly optimizing myself and my code

There are:

  • forcli, only use method, there will be a special article on how to build their owncli. And thank youCircle circleCli code explanation ~
  • forwebpackI used itwebpack-dev-serverTo start the service, which prints a lot of stuff on the console, so it will be scripted by itself

Here are the github addresses for cli and react-template

  • react-template
  • react-demo-cli

Above article if have wrong place, still ask everybody to point out ~ we progress together ~

Then, share my public account “Web front-end diary” TWO-DIMENSIONAL code, welcome to come to everyone’s attention ~