how to import a CommonJS module as an ECMAScript module All In One

how to import a CommonJS module as an ECMAScript module All In One

CJS vs ESM

.mjs import .cjs module

cjs-module.cjs

const sum = (a, b) => a + b;

// export = sum;
// 'export =' can only be used in TypeScript files.ts(8003)

// ❌
// exports = sum;
// obj = {}
// sum = undefined

// ✅
// exports.sum = sum;
// console.log(`module inner sum`, sum);

// ✅
// module.exports = sum;
// ✅
module.exports = {sum};

esm-module.mjs

export const Add = (a, b) => a + b;

// ✅
// export default Add;

// ✅
export default {Add};

index.mjs

const log = console.log;

// ESM ✅
// import Add from './esm-module.mjs';
// import {Add as add} from './esm-module.mjs';
// log(`Add =`, Add);
// // Add = [Function: Add]
// log(`add =`, add);
// // add = [Function: Add]

import ESM from './esm-module.mjs';
import {Add as add} from './esm-module.mjs';
log(`ESM =`, ESM);
// ESM = { Add: [Function: Add] }
log(`add =`, add);
// add = [Function: Add]

const test1 = ESM.Add(3,4);
const test2 = add(3,4);

if(test1 === 7 && test2 === 7) {
  log(`🚀✅ ESM.Add(3,4) && add(3,4) =`, test1, test2);
} else {
  log(`🚀❌ error`, test);
}


// use CJS as ESM ✅
import obj from './cjs-module.cjs';
import {sum} from './cjs-module.cjs';

log(`obj =`, obj);
// obj = { sum: [Function: sum] }
log(`sum =`, sum);
// sum = [Function: sum]

const result = sum(1,2);

if(result === 3) {
  log(`✅ sum(1,2) =`, result);
} else {
  log(`❌ error`, result);
}

https://github.com/web-full-stack/how-to-use-cjs-module-as-esm-module-in-node.js

'@next/mdx'

https://github.com/vercel/next.js/blob/canary/packages/next-mdx/index.js

https://github.com/vercel/next.js/blob/canary/packages/next-mdx/index.d.ts

// HOF, Higher Order Function ✅

// CJS default export  & anonymous functions
module.exports = (pluginOptions = {}) => (nextConfig = {}) => { return Object.assign({}, nextConfig, {...config})};

update docs for ESM usages

// rename the export anonymous function with whatever
import NextMdx from '@next/mdx'; // ✅

NextMdx()


OR

// alias 
import * as NextMdx from '@next/mdx'; // ✅

NextMdx.default()

https://github.com/vercel/next.js/issues/43665#issuecomment-1340875080

??? PR for doccs

image

demos

fix: NextMdx is not a function bug ✅ NextMdx.default

https://github.com/vercel/next.js/issues/43665#

https://github.com/xgqfrms/ssr-next/commit/819d53c18cb1f876fd28fef4352ae96f31a0e4c6#r92243546

next.config.js => next.config.mjs

const path = require('path')

/** @type {import('next').NextConfig} */

const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  // i18n
  i18n: {
    locales: ['en', 'zh'],
    // defaultLocale: 'en',
    defaultLocale: 'zh',
    // 默認值,不會顯示在 url 路徑中 (zh 不出現)
    // http://localhost:3000/seo/test
    // http://localhost:3000/en/seo/test
  },
}

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [require("remark-prism")], // ✅
  },
});


module.exports = withMDX({
  // Append the default value with md extensions
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  ...nextConfig,
  sassOptions: {
    includePaths: [
      path.join(__dirname, 'styles')
    ],
  },
})



import path from 'path'

import remarkPrism from "remark-prism"
import remarkGfm from "remark-gfm"
// import rehypeHighlight from 'rehype-highlight'

import * as NextMdx from '@next/mdx'; // ✅

// import {nextMDX as NextMdx} from '@next/mdx'; // ❌

// import pkg from '@next/mdx'; // ❌
// const {nextMDX: NextMdx} = pkg; // ❌

/*
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@next/mdx';
const {nextMDX: NextMdx} = pkg;

*/

/** @type {import('next').NextConfig} */


// 默認當前 root 路徑 ✅
const __dirname = path.resolve();

const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  // i18n
  i18n: {
    locales: ['en', 'zh'],
    // defaultLocale: 'en',
    defaultLocale: 'zh',
    // 默認值,不會顯示在 url 路徑中 (zh 不出現)
    // http://localhost:3000/seo/test
    // http://localhost:3000/en/seo/test
  },
}

const withMDX = NextMdx.default({
// const withMDX = NextMdx({ // ❌ TypeError: NextMdx is not a function
// const withMDX = NextMdx.withMDX({ // ❌ TypeError: Cannot read properties of undefined (reading 'withMDX')
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [remarkGfm, remarkPrism], // 二合一 ✅
    // rehypePlugins: [rehypeHighlight],",
  },
});

const CustomNextConfig = withMDX({
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  ...nextConfig,
  sassOptions: {
    includePaths: [
      path.join(__dirname, 'styles')
    ],
  },
});

export default CustomNextConfig;

(🐞 反爬蟲測試!打擊盜版⚠️)如果你看到這個信息, 說明這是一篇剽竊的文章,請訪問 https://www.cnblogs.com/xgqfrms/ 查看原創文章!

refs

ESM

https://nodejs.org/api/esm.html#esm_enabling

https://adamcoster.com/blog/commonjs-and-esm-importexport-compatibility-examples

https://stackoverflow.com/questions/29596714/new-es6-syntax-for-importing-commonjs-amd-modules-i-e-import-foo-require

https://dev.to/iggredible/what-the-heck-are-cjs-amd-umd-and-esm-ikm

https://juejin.im/post/6844904126195695624



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 發佈文章使用:只允許註冊用戶纔可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章