blog icon indicating copy to clipboard operation
blog copied to clipboard

esm commonjs

Open yongheng2016 opened this issue 1 year ago • 0 comments

moduleResolution 总结


mkdir my-project
cd my-project
npm init -y
git init
npx mrm gitignore
npm i lodash lodash-es typescript

  • tsconfig.json
{
  "compilerOptions": {
    "allowJs": true,  // 允许编译js,引入不报错
    "target": "ES6",
    "module": "CommonJS",
    "esModuleInterop": true,  // 用于控制模块导入的方式。当esModuleInterop被设置为true时,TypeScript编译器将使用__importDefault()函数来导入默认导出。这使得在使用CommonJS模块时,可以像使用ES6模块一样导入默认导出。
    "strict": true,
    "outDir": "dist"
  },
  "include": [
    "src/**/*"
  ]
}
  • src/index.ts
// 引入 CommonJS 版本的 lodash
// const _ = require('lodash');
import  _ from "lodash"  // CommonJS版本lodash,没有allowSyntheticDefaultImports情况下 import * as _ from 'lodash'
import {test} from "./test.js"

console.log('commonjs',_.chunk([1, 2, 3, 4], 2));
console.log( test())


// 引入 ESM 版本的 lodash
// import { chunk } from 'lodash-es';
// console.log('esm',chunk([1, 2, 3, 4], 2));

yongheng2016 avatar Apr 25 '23 07:04 yongheng2016