Browserify 可以创建一个包,但是它会随着时间的推移而增长 => 包(script.js)的加载时间会增加。因此,在这种情况下需要对包进行代码拆分(仅在需要时加载特定的部分/数据)。
我正在使用gulp.js、browserify、PHP(这也是我不使用 CRA 或 Next.js 的原因)。
CRA 可以使用React.lazy
+来处理这个问题Suspense
。但是我想通过使用 gulp 来创建我自己的代码分割。如何将道具传递script.js
给component.about.js
并渲染component.about.js
?
/* Gulp (Toolkit) */
export function js (cb) {
const files = glob.sync(path__js().src)
return merge(files.map((file:any) => {
return browserify({
basedir: path__dir(),
debug: false,
entries: file,
extensions: ['.js', '.jsx', '.ts', '.tsx'],
paths: ['./node_modules'],
cache: {},
packageCache: {},
})
.plugin(tsify, var_js().tsconfig.compilerOptions)
.bundle().on('error', (e:any) => cb(e))
.pipe(source("script.js"))
.pipe(buffer())
.pipe(dest(path__js().dest))
.on("end", cb)
}}
<!-- 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>Code-Splitting</title>
</head>
<body>
<div id="root"></div>
<script src="/js/script.js"></script>
</body>
</html>
/* /js/script.js
* A part of bundle code.
*/
import React, {useState, useEffect, useRef} from "react"
export default () => {
useEffect(() => {
const script = document.createElement("script")
script.src = `/js/component.about.js`
script.async = true
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
}
}, [])
return (
<Page__About title="Title: About" />
)
}
/* /js/component.about.js */
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Page__About = void 0;
var Page__About = function (props) {
var title = props.title;
return (React.createElement("section", { className: "block" },
React.createElement("div", { className: "content" },
React.createElement("h2", { className: "title" }, title),
};
exports.Page__About = Page__About;
},{}]},{},[1]);