Skip to content

Latest commit

 

History

History

systemjs-test

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

通过Webpack将react应用打包成systemjs模块,并且在浏览器中加载模块

先通过终端在项目中安装以下包

新建 webpack.config.js 文件 内容如下

const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
  mode: "development",
  entry: "./src/index.js",
  output: {
    filename: "index.js",
    path: path.join(__dirname, "build"),
    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: {
            presets: ["@babel/preset-env", "@babel/preset-react"]
          }
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./src/index.html",
      inject: false
    })
  ],
  externals: ["react", "react-dom", "react-router-dom"] // 这里输入需要不打包的包,也就是在index.js中import的库
}

然后新建文件夹 src 在src目录下新建index.js和index.html两个文件

// index.js
import React from "react"
import ReactDOM from "react-dom"
import App from "./App.js"

// console.log(React)

ReactDOM.render(<App />, document.getElementById("root"))

// App.js
import React from 'react'

const App = () => <div>Hello App</div>

<!-- 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>Document</title>
  <script type="systemjs-importmap">
    {
      "imports": {
        "react": "https://cdn.jsdelivr.net/npm/[email protected]/umd/react.production.min.js",
        "react-dom": "https://cdn.jsdelivr.net/npm/[email protected]/umd/react-dom.production.min.js",
        "react-router-dom": "https://cdn.jsdelivr.net/npm/[email protected]/umd/react-router-dom.min.js"
      }
    }
  </script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/system.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script>
    System.import("./index.js")
  </script>
</body>
</html>