在Webpack 场景下,构建现代JS工程环境所需要 的三种常用工具:Babel、TypeScript、ESLint。
Babel
Babel 是一个开源 JavaScript 转编译器,它能将高版本 —— 如 ES6 代码等价转译为向后兼容,能直接在旧版 JavaScript 引擎运行的低版本代码。
使用
npm i -D @babel/core @babel/preset-env babel-loader
module.exports = {
/* ... */
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader'],
},
],
},
};
接入后,可以使用 .babelrc 文件或 rule.options 属性配置 Babel 功能逻辑。
关于babel-preset-env的配置,可写在.babelrc,package.json中可写一部分(例如browsersList),甚至webpack.config.js里都能写,但这几个地方分优先级,.babelrc优先级最好,为了统一,最好都写在.babelrc
npm i -D @babel/preset-env
module.exports = {
/* ... */
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
],
},
],
},
};
TypeScript
安装依赖
npm i -D typescript ts-loader
配置 Webpack
const path = require('path');
module.exports = {
/* xxx */
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader'
},
],
},
resolve: {
extensions: ['.ts', '.js'],
}
};
3.创建 tsconfig.json 配置文件,并补充 TypeScript 配置信息
// tsconfig.json
{
"compilerOptions": {
"noImplicitAny": true,
"moduleResolution": "node"
}
}
Eslint
一种扩展性极佳的 JavaScript 代码风格检查工具,它能够自动识别违反风格规则的代码并予以修复
Webpack 下,可以使用 eslint-webpack-plugin 接入 ESLint 工具,步骤:
安装依赖
安装 webpack 依赖
yarn add -D webpack webpack-cli
安装 eslint
yarn add -D eslint eslint-webpack-plugin
使用 standard 规范
yarn add -D eslint-config-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node
在项目根目录添加 .eslintrc 配置文件,内容:
// .eslintrc
{
"extends": "standard"
}
3.添加 webpack.config.js 配置文件,补充 eslint-webpack-plugin 配置:
// webpack.config.js
const path = require('path')
const ESLintPlugin = require('eslint-webpack-plugin')
module.exports = {
entry: './src/index',
mode: 'development',
devtool: false,
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
// 添加 eslint-webpack-plugin 插件实例
plugins: [new ESLintPlugin()]
}