首頁  >  文章  >  web前端  >  淺析node esmodule模式下怎麼呼叫commonjs模組

淺析node esmodule模式下怎麼呼叫commonjs模組

青灯夜游
青灯夜游轉載
2022-04-01 20:08:112232瀏覽

這篇文章來繼續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模組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除