systemjs 是一个最小系统加载工具,用来创建插件来处理可替代的场景加载过程,包括加载 CSS 场景和图片,主要运行在浏览器和 NodeJS 中。它是 ES6 浏览器加载程序的的扩展,将应用在本地浏览器中。通常创建的插件名称是模块本身,要是没有特意指定用途,则默认插件名是模块的扩展名称。
缺点:版本兼容性差,对开发者体验不好
通过webpack将react应用打包为systemjs模块,在通过systemjs在浏览器中加载模块
安装配置
npm install webpack@5.17.0
添加文件
{
"name": "systemjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"@babel/cli": "^7.12.10",
"@babel/core": "^7.12.16",
"@babel/preset-env": "^7.12.7",
"@babel/preset-react": "^7.12.7",
"babel-loader": "^8.2.2",
"html-webpack-plugin": "^4.5.1",
"webpack": "^5.8.0",
"webpack-dev-server": "^3.11.2",
"webpack-cli": "^4.2.0",
},
"devDependencies": {
},
"scripts": {
"start": "webpack serve"
},
"author": "",
"license": "ISC"
}
导入以上配置,执行
npm install
指定构建需要的库system
排除公共包打包
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin")
module.exports = {
mode:"development",
entry:"./src/index.js",
output: {
path: path.join(__dirname,"build"),
filename: "index.js",
//指定构建需要的库
libraryTarget: "system"
},
devtool: "source-map",
devServer: {
port:9000,
contentBase:path.join(__dirname,"build"),
historyApiFallback: true
},
module: {
rules:[
{
test:/\.js$/,
exclude:/node_modules/,
use:{
loader: "babel-loader",
options: {
presrts:["@babel/preset-env","@babel/react"]
}
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
inject: false,
template: "./src/index.html"
})
],
//添加打包排除选项
externals:["react","react-dom","react-router-dom"]
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>systemjs-react</title>
<!--按照systemjs模块化的方式引入React框架应用-->
<script type="systemjs-importmap">
{
"imports":{
"react": "https://cdn.jsdelivr.net/npm/react@17.0.1/umd/react.production.min.js",
"react-dom": "https://cdn.jsdelivr.net/npm/react-dom@17.0.1/umd/react-dom.production.min.js",
"react-router-dom": "https://cdn.jsdelivr.net/npm/react-router-dom@5.2.0/umd/react-router-dom.min.js"
}
}
</script>
<!--systemjs-->
<script src="https://cdn.jsdelivr.net/npm/systemjs@6.8.0/dist/system.js"></script>
</head>
<body>
<div id="app"></div>
<script>
//引入具体应用
System.import("./index.js")
</script>
</body>
</html>
import * as React from "react"
import * as ReactDOM from "react-dom"
import App from './App.js'
ReactDOM.render(<App/>,document.getElementById('app'));
import * as React from "react"
export default function App() {
return <div>Hello systemjs</div>
}
Systemjs平时真的用的很少,而且很不友好,一直有冲突,这里是后面要做react和Vue统一模块才选择使用的,平时不建议使用,配置冲突是真的麻烦