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

例如:

使用这个

import webpack from 'webpack';

而不是

var webpack = require('webpack');

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


当前回答

看了无数的文件之后……

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

其他回答

另一种方法是这样写一个npm脚本:"webpack": "babel-node ./node_modules/webpack/bin/webpack",然后像这样运行:

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'
        },

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

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

例子:

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

将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

看了无数的文件之后……

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