简体   繁体   中英

JS bundled with webpack can resolve to submodules but ts/spfx cannot

I have a local lib with a few submodules, I added dynamically a package.json in the dist folder to tell which files I want to expose using "exports".

What I can't figure out is why typescript gives me this error: 在此处输入图像描述

"minimal-module-webpack/omega" is a submodule of "minimal-module-webpack" and should resolve to the omega.js. Here is the package.json placed inside the dist folder:

{
  "main": "./index.js",
  "exports": {
    "./omega": "./omega.js",
    "./beta": "./beta.js",
    "./alpha": "./alpha.js"
  }
}

The same from an webpack project with js: 在此处输入图像描述 在此处输入图像描述

So what could I have been missing here? why this works with js but ts compiler is complaining? Even if I remove the package.json from the dist and use the exports in the root of the lib pointing to the dist tsc still complains.

After extensive reading and trial I used:

tsc --traceResolution

Figured out how the resolution work in typescript. and I realized that the version of typescript that is used in SPFX does nothing with the "exports" property from package.json. this feature is only available starting in typescript 4.5.

I solved by creating the declaration in a types folder and moving them to the dist folder using the afterEmit hook.


const copyTypings = (root) => {
  glob.sync(root + '/**/*.d.ts').map(
    el => fs.copyFileSync(el, el.replace(root, './dist'))
  )
}
//---
//webpack.config.js
apply: (compiler) => {
          compiler.hooks.afterEmit.tap("stuff", (compilation) => {
           copyTypings('./types')
          });
        },
// output from tsc --traceResolution
======== Module name 'design/components/footer' was successfully resolved to 'C:/Code/Monorepo%20Sample%20App/design/dist/components/footer.d.ts'. ========

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM