我想知道我们是否使用了babel loader +所有预设,为什么我们需要将babel-polyfill包含在我们的组件中呢?我只是认为babel-loader应该自己完成所有工作。
这里的例子是https://github.com/reactjs/redux/tree/master/examples
我要问的是:
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import App from './containers/App';
这是包示例:
{
"name": "redux-shopping-cart-example",
"version": "0.0.0",
"description": "Redux shopping-cart example",
"scripts": {
"start": "node server.js",
"test": "cross-env NODE_ENV=test mocha --recursive --compilers js:babel-register",
"test:watch": "npm test -- --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/reactjs/redux.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/reactjs/redux/issues"
},
"homepage": "http://redux.js.org",
"dependencies": {
"babel-polyfill": "^6.3.14",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-redux": "^4.2.1",
"redux": "^3.2.1",
"redux-thunk": "^1.0.3"
},
"devDependencies": {
"babel-core": "^6.3.15",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-react-hmre": "^1.1.1",
"cross-env": "^1.0.7",
"enzyme": "^2.0.0",
"express": "^4.13.3",
"json-loader": "^0.5.3",
"react-addons-test-utils": "^0.14.7",
"redux-logger": "^2.0.1",
"mocha": "^2.2.5",
"node-libs-browser": "^0.5.2",
"webpack": "^1.9.11",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.9.1"
}
}
以下是取自https://github.com/reactjs/redux/tree/master/examples
的webpack配置示例var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
loaders: [ 'babel?presets[]=react,presets[]=es2015,presets[]=react-hmre' ],
exclude: /node_modules/,
include: __dirname
},
{
test: /\.json$/,
loaders: [ 'json' ],
exclude: /node_modules/,
include: __dirname
}
]
}
}
答案 0 :(得分:26)
Babel将您的代码转换为浏览器可以理解的内容,但生成的代码使用的功能可能在每个浏览器中都有效,也可能无效。例如,所有浏览器都不支持Object.assign
,因此babel-polyfill填补了漏洞。它只是一个聚合填充的集合,您通常会包含它们以支持旧版浏览器。
考虑以下代码:
const foo = {
name: 'Homer'
};
const bar = Object.assign({}, foo, {age: '?'});
console.log(Object.keys(foo), Object.keys(bar));
巴别塔将这个转变为差不多相同:
'use strict';
var foo = {
name: 'Homer'
};
var bar = Object.assign({}, foo, { age: '?' });
console.log(Object.keys(foo), Object.keys(bar));
因为这是普通的老派JS语法。但是,这并不意味着所使用的本机函数都在所有浏览器中实现,因此我们需要包含polyfill。