#reactjs #webpack #babeljs #babel-polyfill
#reactjs #webpack #babeljs #babel-полифилл
Вопрос:
Я добавил много настроек, предоставленных Babel или другими из stack overflow, но новые функции ES6, такие как функция стрелки и параметр по умолчанию, все еще находятся в моем bundle.js
The bundle.js имеет содержимое, подобное приведенному ниже:
var nn = function(e={}) {
const {baseClasses: t, newClasses: n, Component: r} = e;
if (!n)
return t;
const a = At()({}, t);
return Object.keys(n).forEach(e=>{
n[e] amp;amp; (a[e] = `${t[e]} ${n[e]}`)
}
),
a
};
В результате, когда я открываю свою страницу в IE11, missing ')'
произошла ошибка, которая указывает на function(e={})
.
Вот мой webpack.config.js:
const entries = require("./config/pages").reduce(function(map, page) {
map[page] = `./src/${page}/index.js`;
return map;
}, {});
module.exports = {
mode: 'development',
entry: ["@babel/polyfill",...entries],
output: {
path: path.resolve(__dirname,'dist'),
publicPath: '/',
filename: 'myapp/static/js/[name]/bundle.js'
},
devtool: 'source-map',
module: require("./config/loaders"),
devServer:{
open: true,
publicPath: '/',
historyApiFallback: true,
disableHostCheck: true
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.ProvidePlugin({
fetch: "isomorphic-fetch",
})
]
};
и ./config/loaders для модуля
module.exports = {
rules: [
{
test: /.(js|jsx)$/,
// exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /.(css|less)$/,
use: ["style-loader", "css-loader", "less-loader"]
},
{
test: /.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 500, //small than 500 use url, otherwise use base64
outputPath:'inquiry/static/img/'
}
}
]
},
{
test: /.(woff(2)?|ttf|eot|svg)(?v=d .d .d )?$/,
use: [{
loader: 'file-loader',
options: {
outputPath: 'myapp/static/fonts/'
}
}]
}
]
};
the .babelrc:
{
"presets": [
// ["@babel/env",
// {
// "targets": {
// "browsers": "ie 11"
// },
// "useBuiltIns": "usage",
// "corejs": "3.0.1",
// }
// ],
["@babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": "3.0.1",
}],
"@babel/react"
],
"plugins": [
["@babel/transform-runtime"],
["@babel/plugin-transform-parameters"],
["@babel/plugin-transform-arrow-functions"],
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"@babel/plugin-proposal-class-properties",
{
"loose": true
}
],
]
}
Кроме того, я импортировал ‘@babel / polyfill’ в свой index.js
PS: Я заметил, что код, содержащий функции ES6, взят из библиотеки Meterial UI в node_modules, поэтому я удалил exclude: /node_modules/,
в правиле загрузчика babel, но он все еще не работает.
Ответ №1:
Я использую webpack 5, и установка целевого значения es5 в webpack.config.js
решила проблему для меня.
module.exports = {
target: 'es5',
...
}
Ответ №2:
Мы ориентируемся на конкретные браузеры в плагине @babel / preset-env, определенном в babel.config.js (это еще один способ объявления конфигурации babel).
presets: [
[
'@babel/preset-env',
{
modules: 'commonjs',
useBuiltIns: 'entry',
targets: {
chrome: '58',
firefox: '54',
ie: '11',
safari: '10',
opera: '44',
edge: '16'
}
}
],
[
'@babel/preset-react'
]
],
plugins: [
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-proposal-class-properties'
]
Пожалуйста, попробуйте целевое объявление, как я опубликовал выше.
Мы используем babel / preset-env 7.3.1, и это corejs
не параметр конфигурации верхнего уровня.
Обновить
Я смог заставить его работать с тестовым проектом, в котором я старался максимально соответствовать вашим настройкам. Вы можете использовать это, чтобы постепенно добавлять сложность и модули, которые вы используете в своем проекте, чтобы изолировать проблему. Эта базовая настройка соответствует вашей и работает хорошо. Вы можете использовать это в качестве отправной точки.
package.json
{
"name": "babel-transprile-error",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@babel/core": "^7.4.3",
"@babel/plugin-proposal-class-properties": "^7.4.0",
"@babel/plugin-proposal-decorators": "^7.4.0",
"@babel/plugin-transform-arrow-functions": "^7.2.0",
"@babel/plugin-transform-parameters": "^7.4.3",
"@babel/plugin-transform-runtime": "^7.4.3",
"@babel/polyfill": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"@babel/preset-react": "^7.0.0",
"@babel/runtime": "^7.4.3",
"babel-loader": "^8.0.5",
"mini-css-extract-plugin": "^0.6.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1"
}
}
webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: ["@babel/polyfill", './src/page/index.js'],
output: {
path: path.resolve(__dirname,'dist'),
publicPath: '/',
filename: 'myapp/static/js/[name]/bundle.js'
},
devtool: 'source-map',
module: require("./config/loaders.js"),
devServer:{
open: true,
publicPath: '/',
historyApiFallback: true,
disableHostCheck: true
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.ProvidePlugin({
fetch: "isomorphic-fetch",
})
]
};
.babelrc
{
"presets": [
// ["@babel/env",
// {
// "targets": {
// "browsers": "ie 11"
// },
// "useBuiltIns": "usage",
// "corejs": "3.0.1",
// }
// ],
["@babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": "3.0.1",
}],
"@babel/react"
],
"plugins": [
["@babel/transform-runtime"],
["@babel/plugin-transform-parameters"],
["@babel/plugin-transform-arrow-functions"],
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"@babel/plugin-proposal-class-properties",
{
"loose": true
}
],
]
}
src/page/index.js
import React, { Component } from 'react';
class someComponent extends React.Component {
constructor(props) {
super(props);
}
method(e = {}) {
console.log(e);
var nn = function(e={}) {
const {baseClasses: t, newClasses: n, Component: r} = e;
if (!n)
return t;
const a = At()({}, t);
return Object.keys(n).forEach(e=>{
n[e] amp;amp; (a[e] = `${t[e]} ${n[e]}`)
}
), a
};
}
render() {
return (
<div onClick={ e => { this.method(e) }}/>
)
}
}
export default someComponent;
config/loaders.js
module.exports = {
rules: [
{
test: /.(js|jsx)$/,
// exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /.(css|less)$/,
use: ["style-loader", "css-loader", "less-loader"]
},
{
test: /.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 500, //small than 500 use url, otherwise use base64
outputPath:'inquiry/static/img/'
}
}
]
},
{
test: /.(woff(2)?|ttf|eot|svg)(?v=d .d .d )?$/,
use: [{
loader: 'file-loader',
options: {
outputPath: 'myapp/static/fonts/'
}
}]
}
]
};
Комментарии:
1. Это не работает. Все еще существуют функции стрелки и параметры по умолчанию.
2.
j=(e,t={})=>n=>{const{withTheme:r=!1,flip:o=null,name:s}=t,u=i()(t,["withTheme","flip","name"])
3. Если я не предоставлю версию corejs,
npm run deploy
возникнет некоторая ошибка. ИНФОРМАЦИЯ ОБ ОШИБКЕ:WARNING: We noticed you're using the `useBuiltIns` option without declaring a core-js version. Currently, we assume version 2.x when no version is passed. Since this default version will likely change in future versions of Babel, we recommend explicitly setting the core-js version you are using via the `corejs` option.
4. Я думаю, что мы не получаем эту ошибку о corejs, потому что мы используем модуль commonjs. Я посмотрю еще раз.
5. Можете ли вы также проверить номера версий, которые я предоставил в package.json?
Ответ №3:
В моем случае это вызвано некоторыми пакетами, которые содержат параметры по умолчанию. Итак, я исправил это, включив node_modules
в babel-loader
:
{
test: /.(jsx?)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/env', '@babel/react'],
plugins: [
'@babel/plugin-transform-runtime',
[
'@babel/plugin-proposal-class-properties',
{
loose: true
}
],
['@babel/plugin-proposal-export-default-from'],
'@babel/plugin-transform-parameters'
]
}
}
/** Include the node_modules folder to fix !! **/
// exclude: /node_modules/ // <== Here is the magic works !
},