AMD 文件类型编译 (下)

前言

上一篇讲述了 rollup.js 编译ES6+语法成 AMD 规范的ES5代码,举的例子是实现最单简单的自执行模块,但是在实际项目中,使用AMD时,存在着定义模块和模块间依赖的情况,本篇将讲述rollup.js处理 AMD 模块依赖编译的配置。

实现例子

  • 编译

demo例子

https://github.com/chenshenhai/rollupjs-note/blob/master/demo/chapter-02-02-02/

npm i

npm run build

## 访问连接 http://127.0.0.1:3000/example/index.html

实现步骤

步骤1: 目录和准备

.
├── build ## rollup.js 编译脚本
│   ├── rollup.config.dev.js
│   ├── rollup.config.js
│   └── rollup.config.prod.js
├── dist ## 编译结果
│   ├── index.js
│   ├── index.js.map
│   └── lib
│       ├── hello.js
│       ├── hello.js.map
│       ├── world.js
│       └── world.js.map
├── example ## 例子
│   ├── index.html
│   └── main.js
├── package.json
└── src ## 源码
    ├── index.js
    └── lib
        ├── hello.js
        └── world.js

安装对应编译的npm模块

## 安装 rollup.js 基础模块
npm i --save-dev rollup 

## 安装 rollup.js 编译本地开发服务插件
npm i --save-dev rollup-plugin-serve

## 安装 rollup.js 编译代码混淆插件
npm i --save-dev rollup-plugin-uglify

## 安装 rollup.js 编译ES6+的 babel 模块
npm i --save-dev @rollup/plugin-babel @babel/core @babel/preset-env

步骤2: rollup配置

  • 编译基本配置 ./build/rollup.config.js
const path = require('path');
const { babel } = require('@rollup/plugin-babel');

const resolveFile = function(filePath) {
  return path.join(__dirname, '..', filePath)
}

const babelOptions = {
  "presets": ['@babel/preset-env'],
}

const plugins = [
  babel(babelOptions),
]

module.exports = [
  {
    input: resolveFile('src/index.js'),
    output: {
      file: resolveFile('dist/index.js'),
      format: 'amd',
    }, 
    external: ['lib/hello', 'lib/world'],
    plugins,
  },

  {
    input: resolveFile('src/lib/hello.js'),
    output: {
      file: resolveFile('dist/lib/hello.js'),
      format: 'amd',
      amd: {
        id: 'lib/hello'
      },
    }, 
    plugins,
  },

  {
    input: resolveFile('src/lib/world.js'),
    output: {
      file: resolveFile('dist/lib/world.js'),
      format: 'amd',
      amd: {
        id: 'lib/world'
      },
    }, 
    plugins,
  },
]
  • 开发模式配置基本 ./build/rollup.config.dev.js
const path = require('path');
const serve = require('rollup-plugin-serve');
const configList = require('./rollup.config');

const resolveFile = function(filePath) {
  return path.join(__dirname, '..', filePath)
}
const PORT = 3000;

configList.map((config, index) => {

  config.output.sourcemap = true;

  if( index === 0 ) {
    config.plugins = [
      ...config.plugins,
      ...[
        serve({
          port: PORT,
          contentBase: [resolveFile('')]
        })
      ]
    ]
  }

  return config;
})

module.exports = configList;
  • 生产模式配置基本 ./build/rollup.config.build.js
const { uglify } = require('rollup-plugin-uglify');
const configList = require('./rollup.config');

configList.map((config, index) => {

  config.output.sourcemap = false;
  config.plugins = [
    ...config.plugins,
    ...[
      uglify()
    ]
  ]

  return config;
})

module.exports = configList;
  • ./package.json配置编译执行脚本
    {
    "scripts": {
      "build": "node_modules/.bin/rollup -c ./build/rollup.config.prod.js",
      "dev": "node_modules/.bin/rollup -w -c ./build/rollup.config.dev.js"
    }
    }
    

步骤3: 待编译ES6源码

  • ./src/index.js 源码内容
import hello from 'lib/hello';
import world from 'lib/world';

export default {
  init() {
    const arr1 = [1,2,3];
    const arr2 = [4,5,6];
    console.log([...arr1, ...arr2]);

    hello.init();
    world.init();
  }
}
  • ./src/lib/hello.js 源码内容

export default {
  init() {
    console.log('this lib/hello module')
  }
}
  • ./src/world.js 源码内容
export default {
  init() {
    console.log('this lib/world module')
  }
}

步骤4: 编译结果

  • 在项目目录下执行 npm run build
  • 编译结果在目录 ./dist/
  • 编译成ES5结果为

dist/index.js

define(['lib/hello', 'lib/world'], function (hello, world) { 'use strict';

  hello = hello && Object.prototype.hasOwnProperty.call(hello, 'default') ? hello['default'] : hello;
  world = world && Object.prototype.hasOwnProperty.call(world, 'default') ? world['default'] : world;

  var index = {
    init: function init() {
      var arr1 = [1, 2, 3];
      var arr2 = [4, 5, 6];
      console.log([].concat(arr1, arr2));
      hello.init();
      world.init();
    }
  };

  return index;

});
//# sourceMappingURL=index.js.map

dist/lib/hello.js

define('lib/hello', function () { 'use strict';

  var hello = {
    init: function init() {
      console.log('this lib/hello module');
    }
  };

  return hello;

});
//# sourceMappingURL=hello.js.map

dist/lib/world.js

define('lib/world', function () { 'use strict';

  var world = {
    init: function init() {
      console.log('this lib/world module');
    }
  };

  return world;

});
//# sourceMappingURL=world.js.map

步骤5: 浏览器查看结果

  • example目录./example/index.html
  • example源码
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.bootcss.com/babel-polyfill/6.26.0/polyfill.js"></script>
    <script data-main="main" src="https://cdn.bootcss.com/require.js/2.3.5/require.js"></script>
  </head>
  <body>
    <p>hello world</p> 
  </body>
</html>
  • require.js引用的配置入口 example/main.js文件
requirejs.config({
  baseUrl: '/', 
  paths: {}
});


define(function (require) {
  var demo = require('dist/index');
  demo.init()
});
[1, 2, 3, 4, 5, 6]
this lib/hello module
this lib/world module
>

后记

本篇讲述rollup.js处理 AMD 模块依赖编译的配置处理,AMD的配置就基本到此为止,下一篇将讲述 CommonJS的配置,这个就更多涉及到Node.js模块的ES6+源码编译。

results matching ""

    No results matching ""