Get the App
SLTechnology News&Howtos  ›  Development  › 

How to call commonjs module in node esmodule mode

Shulou Source: shulou.com Published: 2022-06-01 01:44:09 09月21日 Update

In this article, the editor introduces in detail "how to call the commonjs module in node esmodule mode". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to call the commonjs module in node esmodule mode" can help you solve your doubts.

Solution

1. Replace the plug-in

It seems to be nonsense, but it is not. Let's take postcss as an example. In fact, issue has followed up for a long time, but it hasn't been updated yet. I have seen some re-implemented, such as postcss-es-modules (the download volume is not high, so I haven't tried it yet).

Or use plug-ins through the support of the vite/rollup framework itself (I'll talk about how the framework itself handles it later), e.g.

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

2. Through the extension supported by nodejs (in the case of type: "module"), change the file suffix to .cjs, and then import the commonjs module through import default from'* .cjs'; e.g.

/ / utils.cjsfunction sum (a, b) {return a + b} module.exports = {sum} / / index.jsimport utils from'. / utils.js'console.log (utils.sum (1,2))

3. Mark the entry files of different modules through the exports field of package.json (which is also a common practice in most third-party libraries); e.g.

/ / package.json "exports": {"import": ". / index.js", "require": ". / index.cjs"} problem record

1. How does nodejs handle .mjs / .cjs suffix files respectively?

Nodejs always loads .mjs files as esmodule modules and .cjs files as commonjs. When package.json sets type: "module", the .js file is always loaded as esmodule.

After reading this, the article "how to call the commonjs module in node esmodule mode" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself. If you want to know more about the article, please follow the industry information channel.

Tags: Modules files patterns articles processing content suffixes plug-ins frameworks support different proper tripartite practices portals but not can be passed most of the fields commonly used Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Apple MySQL NVidia vpn