Build a plug-in development environment for React's series of tutorials on developing chrome plug-ins

Posted by Devon11 on Sun, 07 Nov 2021 23:02:40 +0100


Following the basic introduction of chrome plug-ins in the last article, let's start to really practice the development of plug-ins. The first part starts with the construction of development environment. This part is also a part that is quite different between plug-in development and web spa application development

Expected target

The expected goal is to build a plug-in development environment of React+TS+Antd to support build to generate all files required by plug-ins

The final ideal build directory should be close to the following form:

├─ favicon.ico         <--You can't use this without it
├─ index.html          <--popup Entry page
├─ insert.js           <--Inserted into the target page js(Not necessary, depending on business needs, as will be mentioned in the notes below)
├─ manifest.json       <--Configuration files for plug-ins
├─ /static
|  ├─ /css
|  |  ├─ content.css   <--content Page style (it will pollute with the target page)
|  |  └─ main.css      <--popup Page style (does not contaminate the target page)
|  ├─ /js
|  |  ├─ background.js <--background script
|  |  ├─ content.js    <--content script
|  |  └─ main.js       <--popup script
|  └─ /media           <--Image resource storage directory of the project

The above includes the pop, content and background components required by the plug-in

Construction practice of development environment

Create react app build standard react project

Here I use the scaffolding create react app, which is familiar to react developers. If you want to use ts, remember to add the parameters of TS template

Quickly create a new standard react+ts project:

npx create-react-app my-app --template typescript
cd my-app
npm start

After that, you can directly execute npm run ejcet to expose the configuration of the webpack. Later, you need to modify the webpack

Engineering Development Directory configuration

Here, I refer to this blog to configure the development directory. You can modify it according to your own style: https://zhuanlan.zhihu.com/p/137793202

    ├─ /config              <--Configuration directory (by) eject (generated)
    ├─ /public              <--popup Entry page
    |  ├─ /images           <--Picture catalog
    |  |  ├─ icon.png       <--Plug in Icon
    |  ├─ favicon.ico       <--You can't use this without it
    |  ├─ index.html        <--popup Entry page
    |  ├─ insert.js         <--Inserted into the target page js(Not required, depending on business needs)
    |  ├─ manifest.json     <--Configuration files for plug-ins
    ├─ /scripts             <--Project build run script (by) eject (generated)
    ├─ /src                 <--Development Directory
    |  ├─ /api              <--API public directory
    |  |  ├─ index.js
    |  ├─ /background       <--background script Development Directory
    |  |  ├─ index.js
    |  ├─ /common           <--Common resource directory
    |  |  ├─ /js            <--public js catalogue
    |  |  └─ /stylus        <--Common style catalog demo use stylus)
    |  ├─ /content          <--content script Development Directory
    |  |  ├─ /components    <--content Component directory
    |  |  ├─ /images        <--content Picture catalog
    |  |  ├─ content.styl   <--content style
    |  |  └─ index.js       <--content script Master file
    |  ├─ /popup            <--popup Development Directory
    |  |  ├─ /pages         <--popup page directory
    |  |  ├─ /components    <--popup Component directory
    |  |  ├─ index.js       <--popup Master file
    |  ├─ index.js          <--Project master file, also popup Entry file
    ├─ pakeage.json

Modify the webpack to generate the above build directory

The point is that plug-in development is not like SPA applications. One entry is enough. You need to modify the configuration of webpack so that it can package products that meet the requirements of the above build directory

Set multiple entrances

In order to package the corresponding js files for pop, background and content, you need to set multiple entries, mainly to modify the entry field

Let's modify config/webpack.config.js as follows:

...
entry: {
      main: [
        isEnvDevelopment &&
        require.resolve('react-dev-utils/webpackHotDevClient'),
        paths.appIndexJs,
      ].filter(Boolean),
      content: './src/content/index.js',
      background: './src/background/index.ts'
    }

The core code is located at approximately 173-198 lines

Replace the original entry with an object, and the key of each object corresponds to an entry

Fixed build generated file name

Because the js file name referenced by the configuration in manifest.json is fixed, we need to ensure that the file name of each package remains unchanged (hash value will be added by default). The main work is as follows:

  • Remove the file hash value and delete [contenthash:8], a total of 4 places. (of course, you can also write some tools to try to dynamically modify the manifest.json file during the packaging phase, so this step is unnecessary)
  • Because it is multi entry, you need to change static/js/bundle.js to static/js/[name].bundle.js.
  • Set runtimeChunk to false, otherwise more runtime-background.js, runtime-content.js and runtime-main.js will be generated after build.
  • Comment out splitChunks and cancel subcontracting, otherwise files like 1.chunk.js and 2.chunk.js will be generated.

Continue to modify the above webpack.config.js:

// About 206 lines
 filename: isEnvProduction
          ? 'static/js/[name].js'
          : isEnvDevelopment && 'static/js/[name].bundle.js',

// About 214 lines
chunkFilename: isEnvProduction
          ? 'static/js/[name].chunk.js'
          : isEnvDevelopment && 'static/js/[name].chunk.js',

// About 302 lines
/ chrome Plug in development, cancel subcontracting mechanism
      // splitChunks: {
      //   chunks: 'all',
      //   name: isEnvDevelopment,
      // },
...
runtimeChunk: false

// About 642 lines
new MiniCssExtractPlugin({
        filename: 'static/css/[name].css',
        chunkFilename: 'static/css/[name].chunk.css',
      }),

Set pop not to introduce js of the other two modules

Set index.html to import only main.js, otherwise background/index.js and content/index.js will also be imported into the pop page

// Line 566
new HtmlWebpackPlugin(
          Object.assign(
              {},
              {
                inject: true,
                // html only introduces pop code, and chrome plug-in development cannot introduce content and background code
                chunks: ['main'],
                template: paths.appHtml,
              },
              isEnvProduction
                  ? {
                    minify: {
                      removeComments: true,
                      collapseWhitespace: true,
                      removeRedundantAttributes: true,
                      useShortDoctype: true,
                      removeEmptyAttributes: true,
                      removeStyleLinkTypeAttributes: true,
                      keepClosingSlash: true,
                      minifyJS: true,
                      minifyCSS: true,
                      minifyURLs: true,
                    },
                  }
                  : undefined
          )
      ),

The above basically completed the transformation of webpack

Introducing Antd

This is a widely used UI component library for react. Students in need can have a look

In fact, the introduction method of antd here is the same as that of traditional development. Here is the code. First, install the antd Library:

npm install antd --save

Next, we need to supplement the on-demand loading capability of antd, which is also introduced on the official website. First, install Babel plugin import:

npm install babel-plugin-import --save-dev

Then modify package.json:

"babel": {
        "presets": [
            "react-app"
        ],
+       "plugins": [
+           [
+               "import",
+               {
+                   "libraryName": "antd",
+                   "style": "css"
+               }
+           ]
+       ]
    }

Review summary

  • Ability to build a chrome plug-in development environment based on react+ts+antd
  • Configuration practice of Web pack multi portal
  • Configuration of webpack product name and path

Topics: Front-end React chrome