如何让node运行es6模块文件及其原理详解

2020-06-17 06:37:55易采站长站整理

如果需要单独使用
src
目录下的文件,那就需要把
src
目录下的文件一对一的转码到
lib
目录下:这种方式推荐使用工具 gulp + babel

1.1 用 rollup 把

src
目录下的文件打包成一个文件到
lib/index.js

相关文件:


# rollup.config.js
export default {
input: 'src/index.js',
output: {
file: 'lib/index.js',
format: 'cjs',
},
};

# package.json
{
"scripts": {
"build": "rollup -c"
},
"devDependencies": {
"rollup": "^0.66.4"
}
}

运行命令:


npm run build

结果:


# lib/index.js
'use strict';

var print = str => {
console.log('print: ' + str);
};

print('index');

module.exports = print;

1.2 用 gulp + babel 把

src
目录下的文件一对一的转码到
lib
目录下

相关文件:


# build.js
const gulp = require('gulp');
const babel = require('gulp-babel');

gulp.task('babel', () =>
gulp.src('src/**/*.js')
.pipe(babel({
plugins: ['@babel/plugin-transform-modules-commonjs'] }))
.pipe(gulp.dest('lib'))
);

gulp.series('babel')();

# package.json
{
"scripts": {
"build": "node build.js"
},
"devDependencies": {
"@babel/core": "^7.1.2",
"@babel/plugin-transform-modules-commonjs": "^7.2.0",
"gulp": "^4.0.0",
"gulp-babel": "^8.0.0"
}
}

运行命令:


npm run build

结果:


# lib/index.js
"use strict";

Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;

var _print = _interopRequireDefault(require("./print"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

(0, _print.default)('index');
var _default = _print.default;
exports.default = _default;

# lib/print.js
"use strict";

Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;

var _default = str => {
console.log('print: ' + str);
};

exports.default = _default;

2. hook node 的 require 机制,直接加载 import/export

这种机制一般是通过对

node