我正在为我觉得不应该太难的设置而苦苦挣扎。我希望这三种技术一起工作:
- webpack 打包代码
- babel 以便我能够编写现代 JavaScript
- flow 因为类型检查很有帮助,就像测试和 linter
我已经经历了几次这样的设置,但我在网上找到的文章似乎都没有帮助。
我在我package.json
的run
、flow
和build
. 类型检查yarn run flow
非常有效,babel-node
使用yarn run start
.
但是当我执行时yarn run build
,通过 webpack 出现以下错误:
$ ./node_modules/webpack/bin/webpack.js
Hash: 207d42dac5784520fc99
Version: webpack 3.10.0
Time: 49ms
Asset Size Chunks Chunk Names
bundle.js 2.65 kB 0 [emitted] main
[0] ./src/main.js 181 bytes {0} [built] [failed] [1 error]
ERROR in ./src/main.js
Module parse failed: Unexpected token (3:5)
You may need an appropriate loader to handle this file type.
| // @flow
|
| type Foo = {
| foo: string,
| };
error Command failed with exit code 2.
在我看来,类型注释没有在正确的位置正确删除。可悲的是,如果我直接在 webpack 中指定 babel 选项而不是.babelrc
.
目前,这让我在使用 flow 时捆绑一堆.js
文件时遇到了挫折,而我发现几个插件据说可以简单地使用flow
预设来剥离流注释,这似乎是 flowtype.org 推荐的。
为了重现性,我的项目文件如下所示:
包.json:
{
…
"dependencies": {},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.3",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-flow": "^6.23.0",
"flow-bin": "^0.60.1",
"webpack": "^3.9.1"
},
"scripts": {
"build": "./node_modules/webpack/bin/webpack.js",
"start": "./node_modules/babel-cli/bin/babel-node.js src/main.js",
"flow": "./node_modules/flow-bin/cli.js"
}
}
.flowconfig:
[include]
./src
[ignore]
[libs]
[lints]
[options]
.babelrc:
{
"presets": ["env", "flow"]
}
webpack.config.js:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/main.js',
output: {
path: __dirname,
filename: 'bundle.js',
},
resolve: {
modules: [
path.resolve('./src/'),
'node_modules',
],
extensions: ['.js'],
},
module: {
rules: [
{
test: '/.js$/',
loader: 'babel-loader',
},
],
},
};
src/main.js:
// @flow
type Foo = {
foo: string,
};
const defaultFoo: Foo = {
foo: 'bar',
};
console.log(defaultFoo);