# import动态引入文件
除了在 webpack.config.js
中配置 splitChunk 来分割代码
webpack 还提供了在代码项目文件中手动指明要动态导入文件的方式来,拆分该动态导入文件(以实现代码分离,代码分离 == 分割代码
)
- webpack 提供了两个类似的技术实现动态代码分离。
- 第一种,也是推荐选择的方式,是使用符合 ECMAScript 提案 的 import() 语法 实现动态导入。
- 第二种则是 webpack 的遗留功能,使用 webpack 特定的 require.ensure。--- webpack--动态导入 (opens new window)
此处仅讲解第一种
# 使用
通过 import()
函数的方式来在代码的某个位置引入,示例:
// mian.js
/** 手动指明 文件动态引入 */
document.getElementById("dynamicEl").addEventListener("click", () => {
// webpackChunkName: "dynamic":这是webpack动态导入模块命名的方式
// "dynamic"将来就会作为[name]的值显示。
import(/* webpackChunkName: "bundle_dynamic" */ "./js/dynamic.js")
.then((module) => {
// // dev-log >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
console.log(`[Dev_Log][${"按需加载模块加载成功"}_]_>>>`);
console.log(module);
console.log(module.dynamicFn(2, 1));
})
.catch((err) => {
console.log(`[Dev_Log][${"按需加载模块加载成功"}_]_>>>`, err);
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- 注意: 直接使用这样使用, eslint会对动态导入语法报错,需要修改eslint配置文件(
plugins: ["import"]
, // 解决动态导入import语法报错问题), - 配置
eslint-plugin-import
解决
# 配置eslint-plugin-import
- 安装
npm i eslint-plugin-import -D
1
安装时可能会报错,说
Could not resolve dependency:npm ERR! peer eslint@"^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8" from eslint-plugin-import@2.29.1
,, 其实就是eslint-plugin-import
版本 和 eslint版本不兼容 可参考一下版本npm i eslint@8.57.0 eslint-plugin-import@2.27.5
1
- 配置
.eslintrc.js
oreslint.config.js
// .eslintrc.js
module.exports = {
// 解析选项
parserOptions: {
// ecmaVersion: 6, // ES 语法版本
ecmaVersion: 2020, // 或更高版本
sourceType: "module", // ES 模块化
allowImportExportEverywhere: true, // 不限制eslint对import使用位置
// ecmaFeatures: {
// // ES 其他特性
// jsx: true, // 如果是 React 项目,就需要开启 jsx 语法
// },
},
// 解决动态导入import语法报错问题 --> 实际使用eslint-plugin-import的规则解决的
plugins: ["import"],
// 继承其他规则--继承 Eslint 规则
extends: ["eslint:recommended"],
// 环境配置
env: {
node: true, // 启用node中全局变量
browser: true, // 启用浏览器中全局变量
},
// 其他规则详见:https://eslint.bootcss.com/docs/user-guide/configuring
// 具体检查规则
rules: {
// "no-var": "warn", // 不能使用 var 定义变量
},
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
- 关于
parserOptions
配置ecmaVersion: 2020
的解释
若使用
ecmaVersion: 6, // ES 语法版本
1
可能会报错
error: 'import' and 'export' may only appear at thetop level
1
使用
ecmaVersion: 2020, // ES 语法版本
1
就不会报错了,原因如下
This release adds support for ES2020 syntax, which includes support for Dynamic Imports and BigInt. This can be enabled using ecmaVersion: 2020 in your configuration file.
# 效果
页面只有执行到对应的动态导入代码文件时,才会发出网络请求加载