This is implemented via babel-plugin-import
Webpack in react-scripts disables the ability to modify the Babel configuration, as shown in the create-react-app scaffolding source code.
This means that changing the Babel configuration by creating a new.babelrc file in the root directory does not work. This can be done by rewriting the webpack configuration in create-react-app as follows:
-
NPM I babel-plugin-import -d install the Babel plugin.
-
NPM I react-app-rewired customize-cra -d rewrite webPack configuration plugin
-
The react component library is @jdcfe/yep-react, and the code is as follows:
const { override, fixBabelImports } = require("customize-cra"); module.exports = override( fixBabelImports("import", { libraryName: "@jdcfe/yep-react".// Component library name libraryDirectory: "es".// Component library path style: "css".// CSS files will be loaded. If set to true, SCSS files will be loaded}));Copy the code
-
To modify scripts in package.json, run the following command:
"scripts": { "start": "react-app-rewired start"."build": "react-app-rewired build"."test": "react-app-rewired test"."eject": "react-app-rewired eject" } Copy the code
-
Reference the Button component in your project
import { Button } from '@jdcfe/yep-react'; Copy the code
NPM run build will compile in Babel:
import { Button } from '@jdcfe/yep-react/es/Button'; require('@jdcfe/yep-react/es/Button/style'); Copy the code
Note: The style file of the component in the converted component library should be placed under the style folder, otherwise an error will be reported as follows:
Cannot find module: '@jdcfe/yep-react/es/button/style'. Make sure this package is installed.
You can install this package by running: npm install @jdcfe/yep-react/es/button/style.
Copy the code
Component libraries support Tree Shaking
What is tree shaking? AST is a Syntax Tree derived from the Syntax analysis of JS code. The AST syntax tree converts every statement of a JS code into a node in the tree. DCE Dead Code Elimination The Elimination of unwanted Code without changing the result of Code execution.
Webpack 4X already uses Tree Shaking technology. By setting the parameter “sideEffects”: false in the component library package.json file, it tells WebPack that it can be bold to remove unused modules when packaging. At this point, the user does not need to do anything when using the component library in the project, and can reference JS resources as needed. But sideEffects set to false will result in the component’s style not being referenced because of the code that introduced CSS styles: Import ‘./dist/index.css’, it just introduces styles, unlike other JS modules that make calls behind them, removing CSS styles when shaking in tree shaking. To configure sideEffects, exclude CSS files:
"sideEffects": [
"dist/index.css"
]
Copy the code
With this tree shaking approach, component libraries can be loaded on demand. Packaged files remove unused component code and save configuration for users.