上一章講的是樣式裝載相關的loader,這一章見得是腳本加載相關的loader
node
$ mkdir 0x012-transliling-loader $ cd 0x012-transliling-loader $ npm init -y $ npm install --save-dev webpack $ touch ./src/index.js $ vim webpack.config.js // ./webpack.config.js const path = require('path'); module.exports = { entry : { 'index': ['./src/index.js'], }, output: { path : path.join(__dirname, 'dist'), filename: '[name].bundle.js' } ;
babel-laoder
加載es6
安裝依賴webpack
$ cnpm install --save-dev babel-loader babel-core babel-preset-env
修改配置git
const path = require('path'); module.exports = { entry : { 'index': ['./src/index.js'], }, output: { path : path.join(__dirname, 'dist'), filename: '[name].bundle.js' }, module: { rules: [ { test : /\.js$/, exclude: /node_modules/, use : { loader: "babel-loader" } } ] } } ;
添加babel
配置文件es6
$ vim ./.babelrc // ./.babelrc { "presets": ["es2015"] }
使用es6
編寫腳本github
$ vim ./src/index.js // ./src/index.js let sayHello = () => { console.log('hello webpack') } sayHello();
打包並查看結果web
// ./dist/index.bundle.js /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var sayHello = function sayHello() { console.log('hello webpack'); }; sayHello(); /***/ }) /******/ ]);
能夠看到,es6
語法被自動轉化成了es5
typescript
更多配置請查閱webpack關於babel-loader章節npm
awesome-typescript-loader
加載typescript
安裝依賴json
$ cnpm install --save-dev awesome-typescript-loader
修改配置vim
const path = require('path'); module.exports = { entry : { 'index': ['./src/index.ts'], }, output : { path : path.join(__dirname, 'dist'), filename: '[name].bundle.js' }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] }, module : { rules: [ { test : /\.tsx?$/, loader: 'awesome-typescript-loader' } ] } } ;
添加typescript
的配置
$ vim ./tsconfig.json // ./tsconfig.json { "compilerOptions": { "noImplicitAny": true, "removeComments": true }, "awesomeTypescriptLoaderOptions": { /* ... */ } }
編寫index.ts
class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } let greeter = new Greeter("world");
編譯並查看結果
/* 1 */ /***/ (function(module, exports) { var Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter; }()); var greeter = new Greeter("world"); /***/ }) /******/ ]);
能夠看出,typescript
被自動轉化成了js
其餘更多配置,請查閱awesome-typescript-loader相關說明