1. npm 命令
mkdir react-webpack-openlayer cd react-webpack-openlayer npm init npm i react react-dom -D npm i webpack webpack-cli webpack-dev-server -D npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev npm i css-loader style-loader npm i ol
2.package.json
{ "name": "react-webpack-openlayer", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server" }, "author": "", "license": "ISC", "dependencies": {}, "devDependencies": { "@babel/core": "^7.4.4", "@babel/preset-env": "^7.4.4", "@babel/preset-react": "^7.0.0", "babel-loader": "^8.0.6", "css-loader": "^2.1.1", "ol": "^5.3.2", "react": "^16.8.6", "react-dom": "^16.8.6", "style-loader": "^0.23.1", "webpack": "^4.31.0", "webpack-cli": "^3.3.2", "webpack-dev-server": "^3.3.1" } }
3.webpack.config.js
const path = require('path') module.exports = { devtool: "source-map", entry: { entry: './src/Main.js', }, output: { path: __dirname, filename: 'index1.js' }, resolve: { alias: { src: path.resolve(__dirname, 'src/') } }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.css$/, exclude: /node_modules/, use: [ 'style-loader', { loader: 'css-loader', options: { modules: true, }, }, ], } ] }, devServer: { inline: true, open: 'Chrome' } }
4..babelrc
{ "presets": ["@babel/preset-env", "@babel/preset-react"] }
5.index.html
Roles and Privileges
6.Main.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(, document.getElementById('app') )
7.App.js
import React from 'react'; import Map from "./Map"; class App extends React.Component { render() { return () } } export default App
8.Map.js
import React, { Component } from "react"; import Map from 'ol/Map.js'; import View from 'ol/View.js'; import TileLayer from 'ol/layer/Tile.js'; import XYZ from 'ol/source/XYZ.js'; import OlSourceOSM from "ol/source/OSM"; class PublicMap extends Component { constructor(props) { super(props); let modelDistribution = require('./config/modelDistribution.json'); this.mapConfig=modelDistribution.map this.initMap(); } componentDidMount() { this.olmap.setTarget("map"); } initMap(){ this.olmap = new Map({ target: null, layers: [ new TileLayer({ source: new XYZ({ url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}" }) }) ], view: new View({ projection: 'EPSG:4326', center:[-83.44, 42.60], zoom: 12 }) }); } render() { return (); } } export default PublicMap;
9. 效果图: