Coder Social home page Coder Social logo

react-webpack-cli's Introduction

webpack搭建react

1. 步骤:

  1. 初始化项目
  2. 安装webpackwebpack-cli,配置webpack.config.js,(考虑生产和测试环境下的配置js)。
  3. html、js、css文件操作操作。使用插件和loader完成。
  4. 引入typescriptreact
  5. 使用eslint、prettier
  6. 使用别名、省略扩展名和devServer

2. 实现

1. 初始化项目
npm init
  • 将生成的package.json文件的"main": "index.js" 值改为"private": true
2. 安装webpackwebpack-cli, 配置webpack.config.js
  • 这里使用yarn
yarn add webpack webpack-cli -D
  • 创建src文件夹,创建一个测试index.js(用于测试wepack的配置,后面会删除,改为tsx
const temporary = () => {
  console.log('test react webpack cli');
};

temporary();
  • 创建config文件夹,在分别创建webpack.config.jswebpack.dev.config.jswebpack.pro.config.js(这里要先安装webpack-merge包,命令yarn add webpack-merge -D

    基础配置在webpack.config.js

    测试相关配置在webpack.dev.config.js

    生产相关配置在webpack.pro.config.js

    相关配置具体可查看🔗,代码如下:

// webpack.config.js
const path = require('path');
const { merge } = require('webpack-merge');
const devConfig = require('./webpack.dev.config.js');
const proConfig = require('./webpack.pro.config.js');

const config = {
  mode: 'production', // 模式
  entry: path.resolve(__dirname, '../src/index.js'), // 入口文件
  output: {
    filename: 'static/js/[name].[contenthash:8].js', // 输入文件名
    path: path.resolve(__dirname, '../build'), // 输入路径
    clean: true, // 清空原打包文件
  },
};

module.exports = (env, argv) => {
  // 开发环境
  if (argv.mode === 'development') {
    return merge(config, devConfig);
  }
  // 生产环境
  if (argv.mode === 'production') {
    return merge(config, proConfig);
  }
};

// webpack.dev.config.js
module.exports = {
  mode: 'development',
  devtool: 'cheap-module-source-map',
};

// webpack.pro.config.js
module.exports = {
  mode: 'production',
  devtool: 'source-map',
};
  • 配置package.jsonscript脚本
{
  "scripts": {
    "build:dev": "webpack --config ./config/webpack.config.js --mode=development",
    "build:pro": "webpack --config ./config/webpack.config.js --mode=production",
    "test": "echo \"Error: no test specified\" && exit 1"
  }
}
  • 执行yarn build:devyarn build:pro分别对应测试打包和生产打包
3. 对html、js、css文件操作操作。使用插件和loader
  • js引入到html文件,使用html-webpack-plugin插件 🔗.

    1. 创建public文件夹,新建index.html
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <link rel="icon" href="favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="theme-color" content="#000000" />
        <meta name="description" content="react-lowcode-manage" />
        <title>react-webpack-cli</title>
      </head>
      <body>
        <noscript>运行该应用,需要启动浏览器对 JavaScript 的支持</noscript>
        <div id="root"></div>
      </body>
    </html>
    1. 使用插件yarn add html-webpack-plugin -D,在webpack.config.js中加上插件
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    plugins: [
    		// 将js引入html
    		new HtmlWebpackPlugin({
    			template: path.resolve(__dirname, '../public/index.html'), // 输入index.html
    			favicon: path.resolve(__dirname, '../public/favicon.ico'), // favicon图标
    		}),
      ]
  • 使用less,然后对css进行打包、分离、压缩

    1. 安装less

      yarn add css-loader less less-loader -D

      less-loader 将 less 文件转换成 css, css-loader 加载 css 文件。

    2. 打包、分离css,使用mini-css-extract-plugin插件,将css文件单独打包

      yarn add mini-css-extract-plugin -D

    3. 压缩css,使用css-minimizer-webpack-plugin

      yarn add css-minimizer-webpack-plugin -D

    4. 添加浏览器前缀,使用postcss-loader插件

      yarn add postcss-loader autoprefixer -D

    5. 统一起来:

      yarn add css-loader less less-loader mini-css-extract-plugin css-minimizer-webpack-plugin postcss-loader autoprefixer -D

    webpack.config.js配置如下:

    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
    const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin');
    
    module: {
    		rules: [
    			// 使用 less
    			{
    				test: /\.less$/i,
    				use: [
    					MiniCssExtractPlugin.loader,
    					'css-loader',
    					{
    						loader: 'postcss-loader',
    						options: {
    							postcssOptions: {
    								plugins: [require('autoprefixer')],
    							},
    						},
    					},
    					'less-loader',
    				],
    			},
    		],
    	},
      plugins: [
        // 提取css
    		new MiniCssExtractPlugin({
    			filename: 'static/css/[name].[contenthash:8].css',
    		}),
      ],
      optimization: {
    		minimizer: [
    			new CssMinimizerWebpackPlugin(), // 压缩css
    		],
    	},
  • 使用label,将es6转为es5

    1. 安装babel

      yarn add babel-loader @babel/preset-env @babel/core -D

      module: {
        rules: [
          {
            test: /\.(js|mjs|jsx|ts|tsx)$/i,
            include: path.resolve(__dirname, '../src'),
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
              },
            },
          },
        ];
      }
4. 引入typescriptreact
  • 安装初始化typescript

    yarn add typescript ts-loader -D

    初始化npx tsc --init生产tsconfig.json

    module: {
      rules: [
        // 使用ts
        {
          test: /\.ts$/i,
          use: ['ts-loader'],
        },
      ];
    }

    tsconfig.json配置如下:

    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx"
      },
      "include": ["src"]
    }
  • 安装react, 配置 babel 解析 react

    yarn add react react-dom

    使用声明文件:yarn add @types/react @types/react-dom -D

    使用babel转义react 文件:yarn add @babel/polyfill @babel/preset-react -D

    module: {
      rules: [
        {
          test: /\.(js|mjs|jsx|ts|tsx)$/i,
          include: path.resolve(__dirname, '../src'),
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env', '@babel/preset-react'],
            },
          },
        },
      ];
    }

    ps:记得将webpack.config.js的入口文件改为对应的文件

5. 使用eslint、prettier
  • 安装prettier格式化代码

    yarn add --dev --exact prettier

    1. 创建.prettierrc文件
    {
      "tabWidth": 2,
      "useTabs": true,
      "singleQuote": true,
      "semi": true
    }
    1. 创建.vscodesettings.son,实现代码代码保存自动格式化
    {
      "typescript.tsdk": "node_modules/typescript/lib",
      "editor.formatOnSave": true // 保存自动格式化
    }
  • 安装eslint实现代码语法检查

    1. 这里使用的是eslint-config-react-app实现相关配置,减少的一些配置。
    2. 使用eslint-config-prettier剔除eslint自带的代码格式化,避免冲突。

    yarn add eslint eslint-config-prettier eslint-config-react-app -D

    package.json中加上,配置eslint

    "eslintConfig": {
    		"extends": [
    			"react-app",
    			"prettier"
    		]
    	}
6. 使用别名、省略扩展名和devServer
  • alias别名,在webpack.config.js配置即可

    resolve: {
    		// 使用别名
    		alias: {
    			'@': path.resolve(__dirname, '../src'),
    		},
    		// 使用扩展名
    		extensions: ['.js', '.json', '.jsx', '.ts', '.tsx'],
    	},
  • 测试环境使用devServer

    1. 安装 yarn add webpack-dev-server -D

    2. webpack.dev.config.js配置

    	devServer: {
    		host: '0.0.0.0',
    		port: '3000',
    		hot: true,
    		open: true,
    	},
    1. package.json中配置script
    "scripts": {
    		"dev": "webpack serve --config ./config/webpack.config.js --mode=development",
    	}

3. 具体配置

具体配置地址如下:[email protected]:yaunfei/react-webpack-cli.git

react-webpack-cli's People

Contributors

yaunfei avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.