我是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; };
如果要将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'] } } ] }