React發佈獨立組件教程(簡要流程步驟)
本開發文檔主要包括開發工具、環境配置、組件化配置和組件化樣例四個部分的講解 ,其中使用ant-design和openlayers庫作爲其中的引用。
1.開發工具
1.1準備事項
JetBrains WebStorm 2019.2 x64 或者 Visual Studio Code
chrome瀏覽器調試
以下用webstorm爲例
1.2環境配置
安裝nodejs並確保node處於Windows環境變量當中,以win10爲例
下圖爲本次所使用的node和npm版本
2.創建目錄
確定一個盤符,在此處打開cmd終端,依次執行如下命令,目錄名以react-simplify-ol爲例:
mkdir react-simplify-ol
cd react-simplify-ol
npm init
3.配置項創建
此時會出現如下,一直回車,部分描述截圖如下(這裏用的另外一個目錄名gitTest):
4.配置項修改
可以發現在目錄中已生成package.json文件,打開並添加保存成如下內容
{
"name": "react-simplify-ol",
"version": "1.0.0",
"description": "just simplify test",
"main": "./lib/index.js",
"scripts": {
"test": "test-ol",
"build": "webpack --progress",
"watch": "webpack --watch --progress",
"publish": "npm publish -registry=http://172.16.1.73:8081/nexus/repository/npm-kfgeo-release/",
"unpublish": "npm unpublish mapdesktop --force -registry=http://172.16.1.73:8081/nexus/repository/npm-kfgeo-release/"
},
"keywords": [
"react",
"react-simplify-ol"
],
"author": "Areo",
"license": "null",
"dependencies": {
"antd": "^3.26.6",
"ol": "^6.1.1",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"devDependencies": {
"autoprefixer": "^9.7.3",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-plugin-import": "^1.13.0",
"babel-plugin-transform-remove-console": "^6.9.4",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.1",
"less": "^3.10.3",
"less-loader": "^5.0.0",
"postcss": "^7.0.26",
"postcss-loader": "^3.0.0",
"style-loader": "^1.1.2",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
}
}
5.依賴安裝
切換成原來的cmd命令行界面,執行如下:
npm install
經過一段時間的安裝後,生成node_modules文件夾。
6.目錄完善
在根目錄建立如下:src文件夾、 .babelrc、 .npmignore、 .npmrc(這些特殊格式文件用webstorm或者vscode創建)和webpack.config.js文件
src先在其中建立components文件夾和index.js,其中components中存放組件庫,index.js作爲輸出文件。
7.示例組件
上述.babelrc寫入如下內容
{
"presets": [
"env"
],
"plugins": [
"transform-react-jsx",
"transform-remove-console",
"transform-runtime",
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}
]
]
}
.npmignore則寫入如下內容
node_modules
dist
example
src
public
.babelrc
.npmrc
app.js
index.html
package-lock.json
webpack.config.js
webpack.prd.js
yarn.lock
yarn-error.log
.npmrc寫入如下內容(可選),詳情見後面:
prefix=D:\node\node_cache
cache=D:\Program Files\nodejs\node_cache
refistry=你的私服地址
always-auth=true()
_auth=a2ZnZW8tcmVsZWFzZTpLZmdlbzIwMTkh
registry=你的私服地址
components文件夾新建一個示例組件假設目錄名爲tableDemo,其中結構如下:
rolMap.js,olTable.js,style.less中代碼如下
olMap.js
//olMap.js
import React from 'react';
import Map from 'ol/Map';
// import Tile from 'ol/layer/Tile';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import View from 'ol/View';
import {fromLonLat, get as getProjection, register} from 'ol/proj';
import XYZ from 'ol/source/XYZ';
// import TileWMS from 'ol/source/TileWMS';
// import proj4 from 'proj4';
import {Input, Icon, message} from 'antd';
import styles from './style.less';
class MapDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
map: {},
location: {
latitude: 0,
longitude: 0,
},
}
}
componentDidMount() {
this.setState({map: this.initMap()});
}
initMap() {
navigator.geolocation.getCurrentPosition(position => {
const {latitude, longitude} = position.coords;
return new Map({
// 設置掛載點爲map
target: 'map',
// 設置圖層
layers: [
// new Tile({
// source: new OSM()
// })
new TileLayer({
source: new XYZ({
url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png'
})
})
],
// 設置地圖的可視區域,center爲中心點,zoom爲縮放的層級
view: new View({
center: fromLonLat([+longitude, +latitude]),
zoom: 13,
//指定地圖投影類型
projection: 'EPSG:3857',
})
})
}, error => message.error({
content: error.message,
duration: 1.5,
maxCount: 1,
}))
};
render() {
return <div id="map" className={styles.mapDiv}>
</div>
}
}
export default MapDemo;
olTable.js
//olTable.js
import React from "react";
import {Table, Divider} from 'antd';
import MapDemo from './olMap';
import styles from './style.less';
export default class extends React.PureComponent {
constructor() {
super();
this.state = {
columns: [
{
title: 'Name',
dataIndex: 'name',
render: text => <a>{text}</a>,
},
{
title: 'Age',
dataIndex: 'age',
},
{
title: 'Address',
dataIndex: 'address',
},
],
data: [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
},
{
key: '4',
name: 'Disabled User',
age: 99,
address: 'Sidney No. 1 Lake Park',
},
],
title: <h2>地圖表格測試</h2>
}
}
componentDidMount() {
console.log('OlTableDemo\' props', this.props);
}
render() {
const {title, columns, data} = this.state;
return <div className={styles.mainWrapper}>
{title}
<MapDemo/>
<Divider/>
<Table columns={columns} dataSource={data} pagination={false} bordered/>
</div>
}
}
style.less
.mainWrapper {
@h-bg: #ffef87;
padding: 20px;
.mapDiv {
width: 100%;
height: 600px;
}
h2 {
box-shadow: 0 2px 12px 0 rgba(13, 13, 13, 0.16);
background-color: @h-bg;
border-radius: 16px;
text-align: center;
color: #fff;
}
}
其中olTable.js作爲該組件的源和輸出,在index.js中引入並輸出這個組件庫。
這裏爲了輸出多個組件庫從而不能使用export default方法,爲了規範起見輸出組件名後添加component後綴。
index.js
import OlTable from "components/tableDemo/olTable";
const exportDemo = {
OlTable,
};
export default exportDemo; //exportDemo爲例,記住這個名稱
8*.組件輸出配置(重要)
配置webpack壓縮轉義並打包輸出該組件庫,編輯目錄下的webpack.config.js,複製以下代碼進去:
webpack.config.js
const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const projectRoot = path.resolve(__dirname, './');
module.exports = {
mode: 'production',
entry: {
index: './src/index.js' //對應src下的index.js
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, "lib"), //這裏一定要和package.json中的main對應
libraryTarget: 'commonjs2'
},
resolve: {
//配置在查找文件的過程中用到的後綴列表
extensions: ['.js', 'jsx', '.less', '.css'],
//如果webpack 在 resolve.root 或者 resolve.modulesDirectories 實在找不到某個模塊了,會去這個目錄中找
//alias通過別名來把原導入路徑映射成一個新的導入路徑
alias: {
'src': path.resolve(__dirname, './src'),
'assets': path.resolve(__dirname, './src/assets'),
'components': path.resolve(__dirname, './src/components'),
'util': path.resolve(__dirname, './src/util'),
}
},
module: {
rules: [
{
test: /\.jsx?$/,
include: projectRoot,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: ['env'],
}
},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{
test: /\.less$/, use: [{
loader: "style-loader"
}, {
loader: "css-loader?modules"
}, {
loader: "less-loader",
options: {
minimize: true,
importLoaders: 1
}
},
{
loader: 'postcss-loader', options: {
plugins: [
require('autoprefixer')()
]
}
}]
},
]
},
plugins: [
new CleanWebpackPlugin()
],
};
9.執行編譯
打開文件目錄下打開cmd終端,執行如下
npm run build
如果不出錯的話,最終在目錄下生成lib文件夾,其中有index.js
這就是這個組件庫最終對外的輸出源,再執行
npm link
npm會將其映射成一個本地的node_modules包。
10.新建一個react項目,引入上述輸出的組件庫
繼上述執行如下cmd終端
cd ../
npm install create-react-app -g
mkdir react-quote-demo
cd react-quote-demo
create-react-app .
生成一個react完整項目
將其中的App.js修改成如下:
App.js
import React from 'react';
import './App.css';
import exportDemo from 'react-simplify-ol';
function App() {
return (
<div className="App">
<kfgeo.OlTable />
</div>
);
}
export default App;
在react-quote-demo中執行cmd終端
npm link react-simplify-ol
其中react-simplify-ol就是我們上述定義的組件庫目錄名,執行成功後在react-quote-demo的node_modules包中即可發現react-simplify-ol。
11.效果預覽
執行cmd終端
npm start
即可在瀏覽器中查看,可以看到我們在react-quote-demo中既沒有引入antd也沒有引入openlayers,但僅僅憑“OlTableDemo”這一單一組件也能完全達到如圖所示實時效果和功能。
11.發佈與下載
在此設置配置項,更改發佈源並從發佈源上下載
在react-simplify-ol中修改package.json中的scripts項。
"scripts": {
"test": "test-ol",
"build": "webpack --progress",
"watch": "webpack --watch --progress",
"publish": "npm publish -registry=你的倉庫地址",
"unpublish": "npm unpublish mapdesktop --force -registry=你的倉庫地址"
},
通過cmd終端執行獲得下載源
npm config get registry 或 npm info express
設置node_modules下載源
npm config set registry 你的倉庫地址
或
npm --registry 你的倉庫地址
或這編輯之前創建的.npmrc文件,寫入以下內容
prefix=D:\node\node_cache
cache=D:\Program Files\nodejs\node_cache(你的node_cahce地址)
refistry=你的倉庫地址
registry=你的倉庫地址
發佈成功後在package.json中的dependencies添加 “react-simplify-ol”: “1.0.0”,
執行npm install即可安裝這個包。
通過cmd終端執行獲得下載源
npm config get registry 或 npm info express
設置node_modules下載源
npm config set registry 你的倉庫地址
或
npm --registry 你的倉庫地址
或這編輯之前創建的.npmrc文件,寫入以下內容
prefix=D:\node\node_cache
cache=D:\Program Files\nodejs\node_cache
refistry=你的倉庫地址
registry=你的倉庫地址
發佈成功後在package.json中的dependencies添加 "react-simplify-ol": "1.0.0",
執行npm install即可安裝這個包。