How to quickly get started with VUE3.0: Entering into learning.
I have been writing a lot of nodejs scripts recently and encountered a problem. After modifying the type: "module" of package.json, some tools cannot be used normally (eg postcss-cli).
This article mainly records how to solve the problem of using commonjs module in esmodule mode.
1. Replace the plug-in;
it seems like nonsense, but it is not. Let's take postcss as an example. In fact, there has been an issue to follow up, but it has not been updated yet. I have seen re-implementations 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 (we will talk about how the framework itself handles it later), eg
// 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. Through the expansion method supported by nodejs (type: "module"), change the file suffix to .cjs, and then you can import the commonjs module through import default from '*.cjs'; eg
// 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. Mark the entry files of different modules through the exports field of package.json (this is also a common practice for most third-party libraries); eg
// package.json "exports": { "import": "./index.js", "require": "./index.cjs" }
1. How does nodejs handle .mjs/.cjs suffix files?
Nodejs always loads .mjs files with the esmodule module and .cjs files with commonjs. When package.json is set to type: "module", .js files are always loaded as esmodule.