babel-plugin-import
babel-plugin-import
通过 babel-plugin-import 按需引入 lodash
准备
-
安装
lodash
、babel-loader
、@babel/core
、babel-plugin-import
依赖yarn add babel-loader @babel/core babel-plugin-import -D
yarn add lodash -S
常规引入 lodash
-
webpack.config.js
配置如下 (不使用任何 loader):const Path = require('path');
module.exports = {
mode: "development",
entry: Path.resolve(process.cwd(), "./src/index.js"),
output: {
filename: "index.js",
path: Path.resolve(process.cwd(), "./build/"),
},
}; -
入口文件引入
lodash
import { flatten, concat } from "lodash";
console.log(flatten, concat); -
执行
webapck build
进行打包编译,编译结果如图所示:Preview如图所示: 只有两句话而已,但是打包出的文件体积巨大。因为他把真个 lodash 文件都打包了,所以我们需要按需引入,减小打包文件的体积
按需引入 lodash -- babel.config.js
-
webpack.config.js
配置babel-loader
如下:{
test: /\.js$/,
use: {
loader: "babel-loader",
},
}, -
webpack.config.js
完整配置如下:const Path = require("path");
module.exports = {
mode: "development",
entry: Path.resolve(process.cwd(), "./src/index.js"),
output: {
filename: "index.js",
path: Path.resolve(process.cwd(), "./build/"),
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "babel-loader",
},
},
],
},
}; -
babel.config.js
配置如下:module.exports = {
plugins: [
[
"import",
{
libraryName: "lodash",
libraryDirectory: "",
},
],
],
}; -
入口文件引入
lodash
import { flatten, concat } from "lodash";
console.log(flatten, concat); -
执行
webapck build
进行打包编译,编译结果如图所示:Preview如图所示: 打包出来的文件体积一下子变得小了许多
按需引入 lodash -- webpack.config.js
-
webpack.config.js
配置babel-loader
如下:{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
plugins: [
[
"import", {
libraryName: "lodash",
libraryDirectory: "",
},
],
],
},
},
} -
webpack.config.js
完整代码如下:const Path = require('path');
module.exports = {
mode: "development",
entry: Path.resolve(process.cwd(), "./src/index.js"),
output: {
filename: "index.js",
path: Path.resolve(process.cwd(), "./build/"),
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
plugins: [
[
"import", {
libraryName: "lodash",
libraryDirectory: "",
},
],
],
},
},
},
],
},
}; -
入口文件引入
lodash
import { flatten, concat } from "lodash";
console.log(flatten, concat); -
执行
webapck build
进行打包编译,编译结果如图所示:Preview如图所示: 打包出来的文件体积一下子变得小了许多