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

例如:

使用这个

import webpack from 'webpack';

而不是

var webpack = require('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

其他回答

Babel 7和Webpack 4的配置

package.json

    ...
    "scripts": {
        "start": "webpack-dev-server --env.dev",
        "build": "webpack --env.prod",
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@babel/core": "^7.0.0",
        "@babel/plugin-proposal-class-properties": "^7.0.0",
        "@babel/preset-env": "^7.0.0",
        "@babel/preset-react": "^7.0.0",
        "@babel/register": "^7.0.0",
        "babel-loader": "^8.0.0",
        ...
        "webpack": "^4.17.2",
        "webpack-cli": "^3.1.0",
        "webpack-config-utils": "^2.3.1",
        "webpack-dev-server": "^3.1.8"

.babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": ["@babel/plugin-proposal-class-properties"]
}

webpack.config.babel.js

import webpack from 'webpack';
import { resolve } from 'path';

import { getIfUtils, removeEmpty } from 'webpack-config-utils';

export default env => {
    const { ifProd, ifNotProd } = getIfUtils(env);

    return {
        mode: ifProd('production', 'development'),
        devtool: ifNotProd('cheap-module-source-map'),
        output: {
            path: resolve(__dirname, ifProd('prod', 'dev')),
            filename: 'bundle.js'
        },

对于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文件。

看了无数的文件之后……

只需安装es2015预置(不是env !!)并将其添加到 .babelrc: { “预设”:( ["es2015", {"modules": false}] ] } 将webpack.config.js重命名为webpack.config.babel.js

编辑:截至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

将es6添加到webpack需要3个步骤

在webpack.config.js中添加 模块:{ 规则:[ { 测试:/ \ . js /美元, 装载机:“babel-loader” } ] } 创建一个。babel。Rc,然后加进去

{ "presets": ["@babel/env", "@babel/react"], “插件”:( [ “@babel / plugin-proposal-class-properties”, ] ] }

在包中。json添加

NPM install @babel/core NPM install @babel/preset-env——save-dev NPM install @babel/preset-react——save-dev NPM install @babel/plugin-proposal-class-properties NPM安装babel-loader——save-dev