如何在 next.js 中加载导出 Typescript 的库 [英] How to load libraries which export Typescript in next.js

查看:99
本文介绍了如何在 next.js 中加载导出 Typescript 的库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从导出 Typescript 的私有库中导入组件时,我们收到以下错误消息:

When trying to import a component from a private library which exports Typescript, we get the following error message:

Module parse failed: Unexpected token (82:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
| // Types
> export type {

我该如何解决?我试图在 tsconfig 文件中明确包含库节点模块:

How could I fix that? I tried to explicitly include the libraries node modules in the tsconfig file:

  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "node_modules/@private-lib/*.*"
  ],
  "exclude": [""]

可惜,无济于事.似乎有可能更改 next.jswebpack 配置,但不幸的是,尝试只推入 Typescript 加载器不起作用:

but unfortunately, to no avail. There seems to be the possibility to change the webpack configuration of next.js, but trying to just shove in a Typescript loader did not work, unfortunately:

module.exports = {
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.(ts|js)x?$/,
      use: [
        options.defaultLoaders.babel,
        {
          loader: "ts-loader",
          options: {
            transpileOnly: true,
            experimentalWatchApi: true,
            onlyCompileBundledFiles: true,
          },
        },
      ],
    });

    return config;
  },
};

它产生这个错误:

./node_modules/process/browser.js
TypeError: /home/blub/bla/website/node_modules/process/browser.js: Property left of AssignmentExpression expected node to be of a type ["LVal"] but instead got "BooleanLiteral"

那么有没有人也遇到过这个问题并且可以指出我正确的方向?这里似乎有很多魔法在起作用,我有点迷失了.

So is anybody out there who also faced this problem and could point me into the right direction? There seems to be a lot of magic at work here and I am kind of lost.

推荐答案

我猜问题出在使用 ts-loader 转译 jsx? 文件,所以它是安全的在 ts-loadder 的情况下只转译 tsx? 文件:

I'm guessing the issue is from transpiling jsx? files with ts-loader so it's safe to just only transpile tsx? file in case of ts-loadder:

webpack: (config, options) => {
  config.module.rules.push({
    test: /\.(ts)x?$/, // Just `tsx?` file only
    use: [
      // options.defaultLoaders.babel, I don't think it's necessary to have this loader too
      {
        loader: "ts-loader",
        options: {
          transpileOnly: true,
          experimentalWatchApi: true,
          onlyCompileBundledFiles: true,
        },
      },
    ],
  });

  return config;
},

还有一件事,如果您的存储库现在使用 jsx? 文件,这意味着在 jsx? 文件中导入 tsx? 文件,您可能必须在 tsconfig.json

One more thing, If your repo is now using jsx? files which means importing tsx? file in a jsx? file, you might have to enable { "allowJs": true } in tsconfig.json

这篇关于如何在 next.js 中加载导出 Typescript 的库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆