import React from 'react';
import ReactDOM from 'react-dom';
// 由於 antd 組件的默認文案是英文,所以需要修改爲中文
import zhCN from 'antd/lib/locale-provider/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
//import 'antd-mobile/dist/antd-mobile.css'; // or 'antd-mobile/dist/antd-mobile.less'
import { Button } from 'antd-mobile';
moment.locale('zh-cn');
class App extends React.Component {
render() {
return (
<div>
<Button>Start</Button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
按需加載的方式官網給我們推薦了兩種;
第一種方式:babel-plugin-import
1、在項目上進行安裝 npm install babel-plugin-import --save
2、裝載
A、野蠻在webpack.config.js裝載
module.exports = function(webpackConfig) {
webpackConfig.babel.plugins.push('transform-runtime');
webpackConfig.babel.plugins.push(['import', {
libraryName: 'antd-mobile',
style: 'css',
}]);
return webpackConfig;
};
B、在根目錄下新建.babelrc進行配置
{
"presets": ["react", "es2015"],
"env": {
"dev": {
"plugins": ["transform-runtime", ["import", { "libraryName": "antd-mobile", "style": true }]] //style參數css時加載css文件,true時加載less
}
}
}
Babel會從當前目錄查找.babelrc文件。這個目錄是文件被編譯的目錄。如果不存在,那麼他會根據目錄樹上尋這個文件,或者在package.json中尋找"babel":{}這個選項。使用"babelrc":false進行設置來停止查找行爲
C、也可以在package.json中配置.babelrc
{
"name":"Antd-Mobile",
"version":"1.0.0",
"babel":{
//在此設置
}
}
"babel": {
"presets": ["react", "es2015"],
"plugins": [["import", [{ "libraryName": "antd-mobile", "style": "css" }]]]
}
module: {
loaders: [
{ test: /\.(js|jsx)$/,
//exclude: /node_modules/,
loader: 'babel-loader'
},//exclude 排除
{ test: /\.less$/,
//exclude: /node_modules/,
loader: 'style!css!postcss!less' },
{ test: /\.css$/,
//exclude: /node_modules/,
loader: 'style!css!postcss' },
{ test:/\.(png|gif|jpg|jpeg|bmp)$/i, loader:'url-loader?limit=5000' }, // 限制大小5kb
{ test:/\.(png|woff|woff2|svg|ttf|eot)($|\?)/i, loader:'url-loader?limit=5000'} // 限制大小小於5k
]
},
2、注意在webpack配置按需加載後需要把package.json中的babel去除;
3、當然還有利用一些腳手架新建項目後根據腳手架,如Create-React-App等,去配置相關的babel即可,萬變不離其宗;
eg:
"extraBabelPlugins": [
"transform-runtime",
['import', { 'libraryName': 'antd-mobile', 'libraryDirectory': 'lib', 'style': true }]
],
import DatePicker from 'antd-mobile/lib/date-picker'; // 加載 JS
import 'antd-mobile/lib/date-picker/style/css'; // 加載 CSS
// import 'antd-mobile/lib/date-picker/style'; // 加載 LESS
效果:
謝謝!歡迎糾正補充~~
附:
antd-mobile官網:https://antd-mobile.gitee.io/docs/react/introduce-cn
babel-plugin-import github:https://github.com/ant-design/babel-plugin-import