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" }]]]
}
插件效果:
注意点:
1、在使用babel-plugin-import时webpack.config.js配置loader加载器时需去除include和exclude,因为antd-mobile的样式依赖都在node_modules,否则它将不会去包里寻找资源;
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