脚本宝典收集整理的这篇文章主要介绍了从零开始的webpack生活-0x012:TranspilingLoader装载脚本,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
0x001 概述
上一章讲的是样式装载相关的loader,这一章见得是脚本加载相关的loader
0x002 环境配置
$ 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'
}
;
0x003 栗子1-babel-laoder
加载es6
-
安装依赖
$ cnpm install --save-dev babel-loader babel-core babel-PReset-env
-
修改配置
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
配置文件
$ vim ./.babelrc
// ./.babelrc
{
"presets": ["es2015"]
}
-
使用es6
编写脚本
$ vim ./src/index.js
// ./src/index.js
let sayHello = () => {
console.log('hello webpack')
}
sayHello();
-
打包并查看结果
// ./dist/index.bundle.js
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
VAR sayHello = function sayHello() {
console.log('hello webpack');
};
sayHello();
/***/ })
/******/ ]);
可以看到,es6
语法被自动转化成了es5
更多配置请查阅webpack关于babel-loader章节
0x004 栗子2-awesome-tyPEscript-loader
加载typescript
-
安装依赖
$ cnpm install --save-dev awesome-typescript-loader
-
修改配置
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相关说明
0x005 资源
以上是脚本宝典为你收集整理的从零开始的webpack生活-0x012:TranspilingLoader装载脚本全部内容,希望文章能够帮你解决从零开始的webpack生活-0x012:TranspilingLoader装载脚本所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。