1.我经历过的项目都是react项目,目前遇到的浏览器兼容问题可以分为两类:
(1)css的问题;
(2)babel-polyfill的问题;
针对第一中问题,我们一般可以直接查询,这里转一个链接,有比较多的css以及其他不同浏览器兼容问题的描述和解决方式:点击打开链接;
第二种问题出现的原因是由于 Babel 默认只转换转各种 ES2015 语法,而不转换新的 API,比如 Promise,以及 Object.assign、Array.from 这些新方法,这时我们需要提供一些 ployfill 来模拟出这样一个提供原生支持功能的浏览器环境。
例如:
参考连接:https://segmentfault.com/a/1190000005128101
参考连接:https://segmentfault.com/q/1010000010352814/a-1020000010356288
主要有两种方式:babel-runtime
和 babel-polyfill
。
babel-runtime
babel-runtime 的作用是模拟 ES2015 环境,包含各种分散的 polyfill 模块,我们可以在自己的模块里单独引入,比如 promise:
import 'babel-runtime/core-js/promise'
它们不会在全局环境添加未实现的方法,只是这样手动引用每个 polyfill 会非常低效,我们可以借助 Runtime transform
插件来自动化处理这一切。
首先使用 npm 安装:
npm install babel-plugin-transform-runtime --save-dev
然后在 webpack 配置文件的 babel-loader 增加选项:
loader: ["babel-loader"],
query: {
plugins: [
"transform-runtime"
],
presets: ['es2015', 'stage-0']
}
babel-polyfill
而 babel-polyfill
是针对全局环境的,引入它浏览器就好像具备了规范里定义的完整的特性,一旦引入,就会跑一个 babel-polyfill
实例。用法如下:
1.安装 babel-polyfill
npm install babel-polyfill --save
2.在入口文件中引用:
import 'babel-polyfill'
这里一定注意是在入口文件。对于我的react项目,我的入口文件是包含route的index.js文件
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute, Redirect } from 'react-router';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import 'babel-polyfill';
import CookiesWrap from './utils/CookiesWrap';
import reducer from './reducers';
import App from './routes/App';
import Login from './routes/login';
const store = createStore(reducer);
//权限控制
function verifyIdentity(nextState, replaceState) {
const userInfo = JSON.parse(CookiesWrap.getCookie('userInfo'));
const userId = CookiesWrap.getCookie('userId');
switch (nextState.routes[1].path) {
case null:
case undefined:
case '/login-password':
case '/download-app':
break;
default:
if (userId && userInfo) {
// 1234表示不同权限
if ((userInfo.roleType[0] === 4 || userInfo.roleType[0] === 1) && nextState.routes[1].path !== '/learn-data-chart') {
replaceState('/learn-data-chart');
}
} else {
replaceState('/');
}
break;
}
}
ReactDOM.render((
<Provider store={store}>
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
<Route path="/exam/:examPaperId" components={ExamPaperPage} />
<Route path="/agreement" components={AgreementPage} />
<Route path="/device-info" components={DeviceInfo} />
<Route path="/" component={App} onEnter={verifyIdentity}>
<IndexRoute component={Login} />
<Route path="/login-password(/forgot)" component={LoginPassword} />
<Route>
{/* 所有新增页面 route 写在 404 的上面 */}
<Route path="/404" component={NotFoundPage} />
<Redirect from="*" to="/404" />
</Route>
</Router>
</Provider >
),
document.getElementById('root'));
registerServiceWorker();