简体   繁体   English

为什么在使用NextJS时不能在Javascript文件中导入或要求Typescript文件?

[英]Why can I not import or require a Typescript file in a Javascript file while using NextJS?

I'm trying to import a factory Typescript file that takes data provided from a client and organizes it in a strict way before passing it to route creation with Next.js. 我正在尝试导入一个工厂Typescript文件,该文件接受来自客户端的数据并以严格的方式对其进行组织,然后再将其传递给Next.js进行路由创建。

I've tried changing the way I import and export files. 我尝试更改导入和导出文件的方式。 I've tried import { ContentfulAssetFactory, LandingPageFactory } from './factory'; 我试过import { ContentfulAssetFactory, LandingPageFactory } from './factory'; and const factory = require('./factory) . const factory = require('./factory)

import { ContentfulAssetFactory, LandingPageFactory } from './factory';

const client = require('./client');

const LANDING_PAGE_CONTENT_TYPE_ID = 'campaignLandingPage';

module.exports = async () => {
  const entries = await client.getEntries({
    content_type: LANDING_PAGE_CONTENT_TYPE_ID,
  });

  const linkedAssets = await entries.includes.Asset.map(asset => {
    return ContentfulAssetFactory.create(asset.fields)
  })

  const items = entries.items.map(item => {
    return LandingPageFactory.create(item.fields, linkedAssets)
  });

  return items;
};
class ContentfulAssetFactory {
    static create(asset: ContentfulAsset) {
        return {
          id: asset.id,
          contentType: asset.contentType,
          url: asset.url,
          title: asset.title
        }
      }
    }
}
class LandingPageFactory {
 static create(page: LandingPage, assets: Array<ContentfulAsset>) {
    const pageImgs = await page.pageImages.map(asset => {
      assets.find(item => {
        if (item.sys.id === asset.sys.id) {

        }
      })
    })

    const lp = {
      campaignTitle: page.campaignTitle,
      promoCode: page.promoCode,
      template: page.template,
      ctaPrimary: page.ctaPrimary,
      ctaPrimaryButtonText: page.ctaPrimaryButtonText,
      ctaPrimaryHyperlink: page.ctaPrimaryHyperlink,
      ctaAlt1: page.ctaAlt1,
      ctaAlt1Hyperlink: page.ctaAlt1Hyperlink,
      ctaAlt1TextColor: page.ctaAlt1TextColor,
      ctaAlt1BackgroundColor: page.ctaAlt1BackgroundColor,
      pageImages: pageImgs
    }
      return lp
  }
}

export {
  ContentfulAsset,
  ContentfulAssetFactory,
  LandingPage,
  LandingPageFactory
}

I'm expecting to be able to import or require the typescript and use the class static functions. 我期望能够导入或要求输入脚本并使用类静态函数。 I'm very confused on why I can't require a file or import it. 我对为什么不需要文件或导入文件感到非常困惑。 The SyntaxError is particularly confusing and I don't know why it's throwing that error when that syntax works in other files. SyntaxError特别令人困惑,我不知道当该语法在其他文件中起作用时为什么会引发该错误。

name:directory name$ yarn dev
yarn run v1.16.0
$ PORT=3000 node --max-old-space-size=4096  server
/Users/name/code/directory/lib/contentful/fetchLandingPages.js:1
import { ContentfulAssetFactory, LandingPageFactory } from './factory';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:718:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/Users/name/code/candidco-web/lib/contentful/index.js:4:27)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
name:directory name$ yarn dev
yarn run v1.16.0
$ PORT=3000 node --max-old-space-size=4096  server
internal/modules/cjs/loader.js:626
    throw err;
    ^

Error: Cannot find module './factory'
Require stack:
- /Users/name/code/directory/lib/contentful/fetchLandingPages.js

update 1 更新1

// next.config.js
if (process.env.NODE_ENV !== 'production') {
  require('dotenv-safe').load();
}
const getRoutes = require('./routes');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const CompressionPlugin = require('compression-webpack-plugin');
const withTypescript = require('@zeit/next-typescript')

const { ANALYZE } = process.env;

module.exports = withTypescript({
  webpack: (config, { isServer }) => {

// various configs

});

node itself does not know about typescript . node本身不了解typescript You should compile it first to regular javascript. 您应该先将其编译为常规javascript。

Typescript is not valid javascript. Typescript无效的javascript。 You have to compile the typescript to javascript before you can import it. 您必须先将打字稿编译为javascript,然后才能导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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