如何在webpack中使用ES6。配置吗? 就像这个回购 https://github.com/kriasoft/react-starter-kit 呢?

例如:

使用这个

import webpack from 'webpack';

而不是

var webpack = require('webpack');

与其说这是一种需求,不如说是一种好奇心。


当前回答

还有一种方法是为node使用require参数:

Node -r babel-register ./node_modules/webpack/bin/webpack . xml

在electron-react-boilerplate中可以找到这种方法,看看build-main和build-renderer脚本。

其他回答

还有一种方法是为node使用require参数:

Node -r babel-register ./node_modules/webpack/bin/webpack . xml

在electron-react-boilerplate中可以找到这种方法,看看build-main和build-renderer脚本。

试着将你的配置命名为webpack.config.babel.js。你应该在项目中包含通音寄存器。在react-router-bootstrap的例子。

Webpack依赖于内部的解释来实现此工作。

编辑:截至2021年2月

https://github.com/webpack/webpack-cli/pull/2381


你不能。你必须把它转换成CommonJS,要么用babel要么用esm。

https://github.com/webpack/webpack-cli/issues/282

但是你可以运行webpack -r esm @babel/register

对于TypeScript:直接从https://webpack.js.org/configuration/configuration-languages/

npm install --save-dev typescript ts-node @types/node @types/webpack
# and, if using webpack-dev-server
npm install --save-dev @types/webpack-dev-server

然后继续写你的,例如: webpack.config.ts

import path from 'path';
import webpack from 'webpack';

const config: webpack.Configuration = {
  mode: 'production',
  entry: './foo.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'foo.bundle.js'
  }
};

export default config;

如果你的目标不是commonjs(这是一个要求,因为它依赖于ts-node),你可以使用一个插件来为webpack配置一个单独的tsconfig文件。

这真的很简单,但从任何答案中我都看不出来,所以如果有人和我一样困惑:

只需将.babel附加到你的文件名扩展名之前的部分(假设你已经安装了babel寄存器作为依赖项)。

例子:

mv webpack.config.js webpack.config.babel.js