AOT Loader:Webpack 中的编译时代码预评估

AOT Loader 是一种 Webpack 加载器,支持在编译阶段加载并预先求值代码。与其他异步加载器不同,AOT Loader 允许开发者编写异步代码,并同步导入已解析数据,直接返回 JSON 格式的结果。

使用方法

  1. 安装 AOT Loader
yarn add aot-loader --dev
  1. 导入并预评估文件

在入口文件中导入需要预评估的文件,并使用 ?aot 查询参数标记。

// entry.js
import data from './data?aot';

console.log(data);

data.js 中编写异步代码,并导出结果。

// data.js
const axios = require('axios');

module.exports = async () => {
  const posts = await axios.get('http://example.com/posts.json');
  return { posts };
};
  1. 配置 Webpack

在 Webpack 配置文件中,使用 aot-loader 处理带有 ?aot 查询参数的文件。

// webpack.config.js
module.exports = {
  entry: './entry.js',
  module: {
    rules: [
      {
        test: /.js$/,
        use: 'aot-loader',
      },
    ],
  },
};
zip
aot-loader-master.zip 预估大小:14个文件
folder
aot-loader-master 文件夹
file
.gitignore 13B
file
babel.js 546B
file
package.json 812B
folder
__test__ 文件夹
file
index.test.js 1KB
folder
fixture 文件夹
file
entry.js 54B
file
data.js 63B
folder
__snapshots__ 文件夹
file
index.test.js.snap 4KB
file
LICENSE 1KB
file
index.js 722B
file
README.md 3KB
file
circle.yml 565B
file
.gitattributes 12B
file
.editorconfig 187B
file
yarn.lock 188KB
zip 文件大小:58.99KB