行。我正在引导一个简单的应用程序。我正在使用 flow.js。我使用的预设是 babel-preset-2015、babel-preset-react 和 babel-preset-stage-0。我必须在我的 .babelrc 和 webpack.config 中放置相同的预设才能使其全部工作。例如,如果我从 webpack.config 中删除它们,我会收到错误“React 未定义”。如果我删除 .babelrc 和 babel-register,我会收到一个错误,因为我使用了 import 和 Flow.js 注释。为什么会这样?如果我将预设放在 webpack.config 中,我应该能够删除 .babelrc 或反之亦然。这就是我的代码在一切正常时的样子(减去一些对问题不重要的文件)。
启动 dev.js
require('babel-register')
require('./src/server/index.js')
索引.js
/* @flow */
import Express from 'express'
import path from 'path'
import conf from '../conf/'
const APP_PORT: number = conf.APP_PORT
const PORT = process.env.PORT || APP_PORT
const app: Express = new Express()
// Middleware
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(Express.static(path.join(__dirname, '../', 'client', 'dist')))
// Routes
app.get('*', function (req: Object, res: Object) {
res.render('index')
})
app.listen(PORT, function () {
console.log(`Express server is up on port ${PORT}`)
})
应用程序.js
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(
<h1>First</h1>,
document.getElementById('app')
)
包.json
{
"scripts": {
"start-dev": "set \"NODE_ENV=development\" && babel-node ./start-dev.js",
"start": "set \"NODE_ENV=development\" && node ./start-dev.js",
"flow": "./node_modules/.bin/flow check",
"standard": "node_modules/.bin/standard --verbose | node_modules/.bin/snazzy"
},
"dependencies": {
"ejs": "^2.5.6",
"express": "^4.15.2",
"react": "^15.4.2",
"react-dom": "^15.4.2"
},
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-core": "^6.24.0",
"babel-eslint": "^7.2.1",
"babel-loader": "^6.4.1",
"babel-preset-es2015": "^6.24.0",
"babel-preset-react": "^6.23.0",
"babel-preset-stage-0": "^6.22.0",
"babel-register": "^6.24.0",
"eslint": "^3.18.0",
"eslint-config-standard": "^7.1.0",
"eslint-plugin-flowtype": "^2.30.4",
"eslint-plugin-react": "^6.10.3",
"flow-bin": "^0.42.0",
"snazzy": "^6.0.0",
"standard": "^9.0.2",
"webpack": "^2.3.2"
}
}
.babelrc
{
"passPerPreset": true,
"presets": [
"es2015",
"react",
"stage-0"
]
}
webpack.config.babel.js
'use strict'
import path from 'path'
const publicPath = path.resolve(__dirname, './src/client')
module.exports = {
devtool: '#source-maps',
performance: {
hints: false
},
context: publicPath,
entry: {
bundle: './app.js'
},
output: {
path: path.join(publicPath, 'dist'),
filename: '[name].js',
publicPath: '/dist/'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
'react',
'es2015',
'stage-0'
]
}
}
]
}
}