使用 rollup 搭建react项目

·  阅读 1127

1. 初始化项目

mkdir rollup-learn
cd rollup-*
npm init -y
复制代码
  • cd webpack-*: 用到了 glob 语法,可自行了解
  • npm init -y: 迅速初始化 npm 项目

2. 安装

  1. 下载 rollup 依赖
    npm i -D rollup rollup-plugin-commonjs @rollup/plugin-node-resolve rollup-plugin-clear rollup-plugin-terser
    复制代码
    • rollup-plugin-commonjs的作用:将CommonJS模块转换为ESM
    • rollup-plugin-node-resolve的作用:帮助 Rollup 查找外部模块,可以直接node_modules模块
    • rollup-plugin-clear: 在打包前删除不需要的文件或者清空输出目录
    • rollup-plugin-terser: 压缩代码
  2. 下载 typescript 相关
    npm i -D rollup-plugin-typescript2
    复制代码
    • typescript rollup-plugin-typescript2: 对 ts 代码进行处理
  3. 下载 babel 相关
    npm i -D @babel/core @babel/preset-env @babel/preset-react @babel/plugin-transform-runtime rollup-plugin-babel
    复制代码
    • rollup-plugin-babel的作用:对es6代码进行babel转化
    • @babel/plugin-transform-runtime: 避免编译输出的重复问题
    • rollup-plugin-babel: 在rollup.config.js中配置babel
  4. 下载 scss相关的plugin
    npm i -D sass rollup-plugin-postcss
    复制代码
  5. 下载 html 相关的依赖
    npm i -D @rollup-plugin-generate-html-template
    复制代码
  6. 下载 react 相关的依赖
    npm i react react-dom 
    npm i -D @types/react @types/react-dom
    复制代码
  7. 下载 启动服务器 相关的plugin, 相当于 webpack 的 webpack-dev-server
    npm i -D rollup-plugin-serve rollup-plugin-livereload
    复制代码
    • rollup-plugin-serve: 启动一个服务器
    • rollup-plugin-livereload: 实时刷新页面
  8. 其他
    • @rollup/plugin-replace: 替换变量

package.json如下:

{
  "name": "rollup-learn",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "rollup -wc",
    "build": "npx rollup -c rollup.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.18.9",
    "@babel/plugin-transform-runtime": "^7.18.9",
    "@babel/preset-env": "^7.18.9",
    "@babel/preset-react": "^7.18.6",
    "@rollup/plugin-babel": "^5.3.1",
    "@rollup/plugin-commonjs": "^22.0.1",
    "@rollup/plugin-node-resolve": "^13.3.0",
    "@rollup/plugin-replace": "^4.0.0",
    "rollup": "^2.77.0",
    "rollup-plugin-clear": "^2.0.7",
    "rollup-plugin-generate-html-template": "^1.7.0",
    "rollup-plugin-livereload": "^2.0.5",
    "rollup-plugin-postcss": "^4.0.2",
    "rollup-plugin-serve": "^2.0.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.32.1",
    "sass": "^1.53.0"
  },
  "dependencies": {
    "@types/react": "^18.0.15",
    "@types/react-dom": "^18.0.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "typescript": "^4.7.4"
  }
}
复制代码

3. 修改文件

最终文件目录如下图

image.png

  • 配置文件
    1. 根目录下的 rollup.config.js文件

      import typescript from 'rollup-plugin-typescript2';
      import scss from 'rollup-plugin-scss';
      import clear from 'rollup-plugin-clear';
      import { nodeResolve } from '@rollup/plugin-node-resolve'
      import commonjs from '@rollup/plugin-commonjs';
      import { babel } from '@rollup/plugin-babel';
      import replace from '@rollup/plugin-replace';
      import { terser } from 'rollup-plugin-terser';
      import serve from 'rollup-plugin-serve';
      import livereload from 'rollup-plugin-livereload';
      import htmlTemplate from 'rollup-plugin-generate-html-template';
      import postcss from 'rollup-plugin-postcss';
      
      export default{
        input: ['./src/index.tsx'],
        output: {
          file: 'dist/main.js',
          format: 'cjs'
        },
        plugins: [
          typescript(), // 会自动读取sconfig.json配置文件
          postcss({ 
            extensions: ['.css'], // 将scss解析成css
            extract: true,
            modules: true,
          }),
          clear({
            targets: ['dist']
          }),
          replace({
            preventAssignment: true,
            'process.env.NODE_ENV': JSON.stringify('production') // 否则会报:process is not defined的错
          }),
          nodeResolve({
          }),
          commonjs(),
          babel(), // 会自动读取babel的配置文件
          terser(),
          serve('dist'),
          livereload('src'), // 当src目录中的文件发生变化时,刷新页面
          htmlTemplate({
            template: 'public/index.html',
            target: 'dist/index.html',
          }),
        ],
        external: [{
          includeDependencies: true,
        }], // 项目中引用的第三方库
      }
      复制代码
    2. 根目录下的.babelrc

      {
        "presets": [
          [
            "@babel/preset-env",
            {
              "modules": false
            }
          ]
        ],
        "plugins": [
          ["@babel/plugin-transform-runtime"]
        ],
        "ignore": [
          "node_modules/**"
        ]
      }
      复制代码
    3. 根目录下的tsconfig.json文件

      {
        "compilerOptions": {
          "target": "es2016",
          "jsx": "react",
          "module": "ESNext",
          "esModuleInterop": true,
          "forceConsistentCasingInFileNames": true,
          "strict": true,
          "skipLibCheck": true,
          "baseUrl": "./",
          "paths": {
            "utils/*": ["src/utils/*"],
            "components/*": ["src/components/*"],
          },
        },
        "include": ["src/**/*", "typings.d.ts"],
        "exclude": ["node_modules"]
      }
      复制代码

      该配置文件中用到了根目录下的typings.d.ts文件

      declare module '*.module.css' {
        const classes : { readonly [key: string]: string }
        export default classes
      } 
      
      declare module '*.module.scss' {
        const classes : { readonly [key: string]: string }
        export default classes
      } 
      复制代码
  • 项目文件
    1. 根目录下中创建 public 文件夹,并添加 index.html 文件 public/index.html 文件内容如下

      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Rollup-react</title>
      </head>
      <body>
        <div id="root"></div>
      </body>
      </html>
      复制代码
    2. 根目录下中创建 src 文件夹, 并添加 index.tsx 文件

      src/index.tsx内容如下:

      // src/index.tsx
      import React from 'react';
      import ReactDOM from 'react-dom/client';
      import App from './App';
      
      const root = document.getElementById('root');
      ReactDOM.createRoot(root!).render(<App name="app" />);
      复制代码
    3. src/App.tsx 文件内容如下:

      import React, { FC } from 'react';
      import { sum } from 'utils/index';
      import styles from './App.module.scss';
      
      console.log('sum', sum(1, 2));
      console.log('styles', styles);
      
      
      interface Props {
        name: string;
      }
      
      const App:FC <Props> = (props) => {
        const { name } = props;
        return (
          <div className={styles.textRed} >{name}</div>
        );
      }
      
      export default App;
      复制代码
    4. src/App.module.scss 文件内容如下:

      .textRed {
        color: red;
      }
      复制代码
    5. src/utils/index.ts 文件内容如下:

      export const sum = (a: number, b: number): number =>( a + b );
      复制代码
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改