出发点: 打开一般npm包package.json你会发现有个main字段,在打开ts的项目包,你会发现增加了fes2015module字段,module字段。这几个字段的却别是什么?怎么针对这些做一些项目的实现及改进?
问题一:main、module的区别
main字段主要用于npm包的索引文件,在依赖查找时能够直接返回对应的module name的js文件;module字段则是支持es module的索引字段。两者的区别在于es module的支持,main一般用于常规的库文件umd格式,在es6的module规范出现后,rollup率先支持了该模式的依赖解析,webpack随后。
问题二:怎么把我的包发布为支持es module的库
rollup可以很好地支持这项特性;
webpack的配置会多一些,单也都不复杂:
"experiments": { outputModule: true },
"output": {
library: {
type: "module",
},
},
输出的代码即为mjs格式的代码。
问题三: fesm2015又是什么
这个和ts有关系,tsc的命令为编译ts语言为js,ts的配置项有一个target字段表示要编译的js版本。
支持 es6 es2015 es2020 esNext等
举例:如果target的值为es2015,那基本编译出来的代码基本不会有变化。
import {from} from 'rxjs';
from(new Promise(e=> {e(2)})).subscribe((e) => {
console.log(e)
})
export const name = 2
const a = () => name
export {a}
编译后的(es2015)
import { from } from 'rxjs';
from(new Promise(function (e) { e(2); })).subscribe(function (e) {
console.log(e);
});
export var name = 2;
var a = function () { return name; };
export { a };
可以看到除了babel编译的一些区别外,基本没有别的变化
umd标准的
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "rxjs"], factory);
}
})(function (require, exports) {
"use strict";
exports.__esModule = true;
exports.a = exports.name = void 0;
var rxjs_1 = require("rxjs");
(0, rxjs_1.from)(new Promise(function (e) { e(2); })).subscribe(function (e) {
console.log(e);
});
exports.name = 2;
var a = function () { return exports.name; };
exports.a = a;
});
tsc编译按照目标设置来进行编译,一些还没普遍应用的语法还需要进行垫片进行补充。
贴一下相关的webpack的配置参数
module.exports = {
mode: 'development',
"experiments": { topLevelAwait: true }, // 开启外部变量的import语法的异步
"experiments": { outputModule: true }, // 输出es module
"output": {
library: {
type: "module", // npm 库文件为es module格式
},
environment: {
module: true,
},
},
"externalsType": "module", // 外部变量的类型,var\ import(需要上面的外部变量参数打开)、script
"externals": {
"rxjs": "rxjs"
}
}
那么参照angular框架的库文件结构,要开发类似的module模式的库,两种途径: 利用ts的打包机制直接输出es2015的文件;2采用webpack或者rollup来配置es module参数。
node-sass报错的解决办法
1.按照node和node-sass版本对应表,安装正确的node版本
2.更换中国镜像源
3.单独安装指定版本的node-sass