Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack + React 单页实践#1:项目初始化 #7

Open
S-T-D opened this issue Feb 23, 2021 · 0 comments
Open

webpack + React 单页实践#1:项目初始化 #7

S-T-D opened this issue Feb 23, 2021 · 0 comments

Comments

@S-T-D
Copy link
Owner

S-T-D commented Feb 23, 2021

这是 webpack 实践系列的第一篇,主要是对我学习和使用 webpack 的一些总结,并配有实际的项目。
文章和项目都基于 webpack 5

主要内容:

初始化项目

mkdir webpack-react-spa-template-project
cd webpack-react-spa-template-project
yarn init

安装

通常来说,建议将 webpack 作为项目依赖安装。

yarn add webpack webpack-cli -D

基础配置

  1. 在项目根目录下新建 dist 目录,用于存放打包后的文件。

  2. 进入 dist目录,新建 index.html,内容如下。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <!-- bundle.js 指向后续 webpack 构建出的文件 -->
        <script src="bundle.js"></script>
    </body>
    </html>
  3. 在项目根目录下新建 src 目录,用于存放业务代码。

  4. 进入 src 目录,新建 index.js ,内容如下。

    document.write('这是一个很漂亮的页面。');    
  5. 在项目根目录下新建 webpack.config.js,内容如下。

    const path = require('path');
    
    module.exports = {
        // 运行模式 development | production
        mode: 'production',
        // 指定构建入口,webpack 将从此文件开始构建整个应用
        entry: './src/index.js',
        // 指定构建好的资源的输出位置
        // 下方配置会在项目的 dist 目录下生成 bundle.js 文件
        output: {
            filename: 'bundle.js',
            path: path.resolve(__dirname, 'dist')
        }
    };
  6. 添加构建脚本到 package.json,内容如下。

    {
      ...
        "scripts": {
            "build": "webpack"
        }, 
      ...
    }

    可以在 webpack 命令后明确指定构建所使用的配置文件:webpack --config my-config.js
    如果不指定,则默认使用 webpack.config.js

  7. 打开终端进入项目,运行构建命令。

    可以看到构建成功了,此时,进入 dist 目录会发现新增了一个 js 文件,也就是 bundle.js

  8. 查看运行效果:直接使用浏览器打开 distindex.html,或者使用 servedist 目录进行托管。

代码地址

webpack-react-spa-template-project

@S-T-D S-T-D changed the title 1. 使用 webpack 搭建 react 单页应用#1:项目初始化 1. webpack + React 单页实践#1:项目初始化 Mar 10, 2021
@S-T-D S-T-D changed the title 1. webpack + React 单页实践#1:项目初始化 webpack + React 单页实践#1:项目初始化 May 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant