浅析node esmodule模式下怎么调用commonjs模块

浅析node esmodule模式下怎么调用commonjs模块,第1张

浅析node esmodule模式下怎么调用commonjs模块 本篇文章来继续node的学习,介绍一下esmodule模式下怎么调用commonjs模块,希望对大家有所帮助!

最近写nodejs脚本较多,遇到一个问题。修改了 package.json 的 type: "module" 后,部分工具无法正常使用(e.g. postcss-cli)。

本文主要是记录下解决在esmodule模式下,如何使用 commonjs 模块的问题。

解决方案

1、更换插件;

好像是废话,其实不然。还是以postcss举例,其实早已有issue跟进,但一直还没更新过来。有看到重新实现的例如 postcss-es-modules(下载量不高,暂时没去试过)。

或者通过vite/rollup框架本身的支持去使用插件(后面再讲框架本身是怎么处理的), e.g.

// tailwind.config.js
export default {
  purge: ['./*.html', './src/**/*.{vue,js,ts,jsx,tsx,css}'],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}
// postcss.config.js
import tailwind from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import tailwindConfig from './tailwind.config.js'

export default {
  plugins: [tailwind(tailwindConfig), autoprefixer],
}
// vite.config.js
css: {
  postcss,
}

2、通过nodejs支持的拓展方式(type: "module"情况下),将文件后缀改为.cjs,然后就可以通过 import default from '*.cjs' 导入 commonjs 模块;e.g.

// utils.cjs
function sum(a, b) {
  return a + b
}
module.exports = {
  sum
}
// index.js
import utils from './utils.js'

console.log(utils.sum(1, 2))

3、通过package.json的 exports 字段分别标志不同模块的入口文件(这也是大部分三方库常用做法); e.g.

// package.json
"exports": {
  "import": "./index.js",
  "require": "./index.cjs"
}
问题记录

1、nodejs分别是怎么处理.mjs/.cjs后缀文件的?

nodejs总是以 esmodule 模块加载.mjs文件,以 commonjs 加载 .cjs 文件。当package.json设置了 type: "module" 时,总是以 esmodule 加载.js文件。

更多node相关知识,请访问:nodejs 教程!

以上就是浅析node esmodule模式下怎么调用commonjs模块的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/690427.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-21
下一篇 2022-04-21

发表评论

登录后才能评论

评论列表(0条)

保存