我对Webpack很新.我想我做错了.我想使用babel将ES6功能转换为ES5功能.所以我做了一些研究,发现了babel-loader.但是,我不确定我在做什么.
我运行了npm install babel-loader --save-dev,它被添加到我的package.json中
// package.json
{ "name": "kanban", "version": "1.0.0", "description": "kanban", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "babel-core": "^6.3.21", "babel-loader": "^6.2.0", "html-webpack-plugin": "^1.7.0", "json-loader": "^0.5.4", "webpack": "^1.12.9" } }
// webpack.config.js
var path = require('path'); var HtmlwebpackPlugin = require('html-webpack-plugin'); const PATHS = { app: path.join(__dirname, 'app'), build: path.join(__dirname, 'build') }; module.exports = { entry: PATHS.app, output: { path: PATHS.build, filename: 'bundle.js' }, plugins: [ new HtmlwebpackPlugin({ title: 'Kanban app' }) ], module: { loaders: [ { test: /\.js$/, loader: 'babel-loader' } ] } };
// app/index.js - 我刚刚在ES6语法中添加了一些随机无用的函数.我希望我能在我的bundle.js文件中看到ES5格式,但它没有改变.它仍然是bundle.js中的ES6语法
var component = require('./component'); var app = document.createElement('div'); document.body.appendChild('app'); app.appendChild(component()); let myJson = { prop: 'myProp' }; let fives = []; nums = [1, 2, 5, 15, 25, 32]; // Statement bodies nums.forEach(function (v) { if (v % 5 === 0) { fives.push(v); } }, this); console.log(fives); let sum = (a, b) => a + b;
// app/component.js
module.exports = function() { var element = document.createElement('h1'); element.innerHTML = 'hello world'; return element; };
dreyescat.. 40
如果要将ES6编译为ES5,则需要安装Babel ES2015预设.
npm install babel-preset-es2015
然后,您需要启用此预设.启用此ES6到ES5编译的一种方法是使用babel-loader查询字符串:
module: { loaders: [ { test: /\.js$/, loader: 'babel-loader?presets[]=es2015' } ] }
或查询选项:
module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', query: { presets: ['es2015'] } } ] }
PhilVarg.. 11
对于webpack 3,模块选项应如下所示
module: { rules: [ { use: { loader:'babel-loader', options: { presets: ['es2015'] } }, test: /\.js$/, exclude: /node_modules/ } ] },
这仍然需要babel-loader
和babel-preset-es2015
如果要将ES6编译为ES5,则需要安装Babel ES2015预设.
npm install babel-preset-es2015
然后,您需要启用此预设.启用此ES6到ES5编译的一种方法是使用babel-loader查询字符串:
module: { loaders: [ { test: /\.js$/, loader: 'babel-loader?presets[]=es2015' } ] }
或查询选项:
module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', query: { presets: ['es2015'] } } ] }
对于webpack 3,模块选项应如下所示
module: { rules: [ { use: { loader:'babel-loader', options: { presets: ['es2015'] } }, test: /\.js$/, exclude: /node_modules/ } ] },
这仍然需要babel-loader
和babel-preset-es2015