当前位置: 首页 > 编程笔记 >

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

田普松
2023-03-14
本文向大家介绍如何让node运行es6模块文件及其原理详解,包括了如何让node运行es6模块文件及其原理详解的使用技巧和注意事项,需要的朋友参考一下

最新版的 node 支持最新版 ECMAScript 几乎所有特性,但有一个特性却一直到现在都还没有支持,那就是从 ES2015 开始定义的模块化机制。而现在我们很多项目都是用 es6 的模块化规范来写代码的,包括 node 项目,所以,node 不能运行 es6 模块文件就会很不便。

让 node 运行 es6 模块文件的方式有两种:

  • 转码 es6 模块为 commonjs 模块
  • hook node 的 require 机制,直接让 node 的 require 加载 import/export

1. 转码 es6 模块为 commonjs 模块

因为 node 支持几乎所有除 import/export 外的语法,所以我们只需要将 import/export 转码成 require/exports,而不需要转码其他语法。

比如下面的项目:

- package.json
- src/
 - index.js
 - print.js
 - ...
# package.json
{
 "main": "lib/index.js"    # 由工具转码 src 目录下源文件到 lib 目录下
}


# src/index.js
import print from './print';

print('index');

export default print;


# src/print.js
export default str => {
 console.log('print: ' + str);
};

因为 src 目录下的源文件都是 es6 模块化规范的,node 并不能直接运行,所以需要转码成 commonjs 规范的代码。

这个过程有两个方案:

  • 如果不会单独使用 src 目录下的某个文件,而仅仅是以 src/index.js 为入口文件使用,可以把 src 目录下的文件打包成一个文件到 lib/index.js:这种方式推荐使用工具 rollup
  • 如果需要单独使用 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 的 require 机制进行 hook,劫持 require 抓取的源文件代码,把源代码转码成 commonjs 规范之后,再传送给 require 机制原本的代码流中。

pirates 之类的第三方 npm 包提供了这种添加 hook 的功能

babel-register 便是使用这种方式达到 node 运行 es6 模块文件的目的的。

2.1 使用 babel-register 直接运行 es6 模块文件

示例目录:

- package.json
- src/
 - entry.js       # 这里多了一个入口文件,专门用于注册 babel-register
 - index.js
 - print.js
 - ...

相关文件:

# package.json
{
 "scripts": {
 "run": "node src/entry.js"
 },
 "devDependencies": {
 "@babel/core": "^7.1.2",
 "@babel/plugin-transform-modules-commonjs": "^7.2.0",
 "@babel/register": "^7.0.0"
 }
}


# src/entry.js       # 入口文件必须使用 commonjs 规范来写,因为还没有注册 hook
require('@babel/register')({
 plugins: ['@babel/plugin-transform-modules-commonjs']
});
require('./index');


# src/index.js
import print from './print';

print('index');


# src/print.js
export default str => {
 console.log('print: ' + str);
};

运行:

npm run run

结果:

# 命令行打印

print: index

这种方式因为中间转码会有额外的性能损耗,所以不建议在生产环境下使用,只建议在开发模式下使用。

2.2 使用babel-node 直接运行 es6 模块文件

babel-node 对 babel-register 进行了封装,提供了在命令行直接运行 es6 模块文件的便捷方式。

示例目录:

- package.json
- src/
 - index.js
 - print.js
 - ...

相关文件:

# package.json
{
 "scripts": {
 "run": "babel-node src/index.js --plugins @babel/plugin-transform-modules-commonjs"
 },
 "devDependencies": {
 "@babel/core": "^7.1.2",
 "@babel/node": "^7.2.0",
 "@babel/plugin-transform-modules-commonjs": "^7.2.0"
 }
}


# src/index.js
import print from './print';

print('index');


# src/print.js
export default str => {
 console.log('print: ' + str);
};

运行:

npm run run

结果:

# 命令行打印

print: index

这种方式也不建议在生产环境下使用,只建议在开发模式下使用。

3. 链接

es6 就是指 ECMAScript 2015

es7 就是指 ECMAScript 2016

es8 就是指 ECMAScript 2017

es9 就是指 ECMAScript 2018

到写这篇文章为止,已发布了 ECMAScript 2018。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小牛知识库。

 类似资料:
  • 原生Node.js模块由Electron支持,但由于Electron具有与给定Node.js不同的 应用二进制接口 (ABI)(由于使用Chromium的 BoringSL 而不是 OpenSSL 等 差异),您使用的原生 模块需要为Electron重新编译。 否则,当您尝试运行您的应用程序时, 将会遇到以下的错误: Error: The module '/path/to/native/modul

  • 本文向大家介绍Nodejs模块载入运行原理,包括了Nodejs模块载入运行原理的使用技巧和注意事项,需要的朋友参考一下 前言 使用Nodejs,就不可避免地引用第三方模块,它们有些是Nodejs自带的(例:http,net...),有些是发布在npm上的(例:mssql,elasticsearch...) 本篇章聚焦3个问题: Nodejs模块的加载过程。 应用启动的过程。 应用如何加载依赖模块。

  • 问题内容: 我正在从https://github.com/moroshko/react- autosuggest 实现一个示例 重要代码如下: 该示例中的复制粘贴代码(有效)在我的项目中出现错误: 如果我删除前缀json !: 这样,我在编译时不会出错(导入已完成)。但是执行时出现错误: 如果我调试它,我可以看到郊区是一个对象,而不是一个数组,因此未定义过滤器功能。 但是在示例中,注释建议是一个数

  • Electron 同样也支持原生模块,但由于和官方的 Node 相比使用了不同的 V8 引擎,如果你想编译原生模块,则需要手动设置 Electron 的 headers 的位置。 原生Node模块的兼容性 当 Node 开始换新的V8引擎版本时,原生模块可能“坏”掉。为确保一切工作正常,你需要检查你想要使用的原生模块是否被 Electron 内置的 Node 支持。你可以在这里查看 Electro

  • Native Node modules are supported by Electron, but since Electron is very likely to use a different V8 version from the Node binary installed on your system, the modules you use will need to be recomp

  • 问题内容: 我需要做类似的事情: 上面的代码无法编译;它抛出。 我尝试使用此处所示的方法,但是我不知道从哪里来。这是没有最终被接受的ES6提案吗?该文章中指向“编程API”的链接将我转至不推荐使用的docs页面。 问题答案: 现在,ECMA确实有动态进口建议。这是在第3阶段。这也可以作为babel-preset使用。 以下是根据您的情况进行条件渲染的方法。 这基本上返回了一个承诺。承诺解决方案有望