如何使用webpack与babel-loader和flow

问题描述 投票:1回答:1

我正在努力应对我觉得不应该太难的设置。我希望这三种技术协同工作:

  • webpack捆绑代码
  • babel让我能够编写现代JavaScript
  • 因为类型检查就像测试和linter一样有用

我已经通过了几个设置,但我在网上找到的文章似乎都没有帮助。


我在我的package.jsonrunflowbuild中定义了3个脚本。与yarn run flow的Typechecking工作完美,使用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似乎推荐的。


对于再现性,我的项目文件如下所示:

的package.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);
javascript webpack babeljs flowtype babel-loader
1个回答
1
投票

下载相关预设并将其添加到webpack.config.js,如下所示:

module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /(node_modules|bower_components)/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['es2015', 'stage-0', 'react']
        }
      }
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.