繁体   English   中英

打字稿/节点意外令牌 *

[英]Typescript/Node Unexpected token *

我正在尝试将我的应用程序节点后端更新为打字稿,但我一直遇到此语法错误:

/Users/Shared/website/src/server.ts:1
(function (exports, require, module, __filename, __dirname) { import * 
as express from 'express';
                                                                 ^

SyntaxError: Unexpected token *

我的 tsconfig/webpack/server 等设置如下:

服务器.ts

import * as express from 'express';
import * as path from 'path';

const app = express();
const port = process.env.PORT || 3000;

app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', function(req, res, next){
    res.sendFile(path.resolve(__dirname, '/public', 'index.html'));
});

app.listen(port, () => console.log(`Listening on port ${port}!`));

webpack.config.json

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const outputDirectory = 'dist';

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: path.join(__dirname, outputDirectory)
    },
    mode: 'development',

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "ts-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" },

            {
                test: /\.scss$/,
                use: [
                    "style-loader", // creates style nodes from JS strings
                    "css-loader", // translates CSS into CommonJS
                    "sass-loader" // compiles Sass to CSS, using Node Sass by default
                ]
            }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    externals: {
    },

    plugins: [
        new CleanWebpackPlugin([outputDirectory]),
        new HtmlWebpackPlugin({
          template: './public/index.html',
          favicon: './public/favicon.gif'
        }),
        new CopyWebpackPlugin([
            { from: 'public' }
        ])
    ]
};

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": false,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react"
    },
    "include": [
        "./src/**/*"
    ],
}

构建过程成功,但我在运行时遇到了语法错误。 我有一个使用 typescript / tsx 设置的 React 前端,它工作得很好。 我似乎只是遇到了 server.ts / node 文件的问题。 我对尝试设置这一切很陌生,但我想练习使用多种技术(react/node/typescript/sass/webpack/etc)制作网站。 到目前为止,除了打字稿/节点关系之外,我拥有一切。

在我意识到未应用 tsconfig 之后,我遇到了同样的问题。

如果

"module": "commonjs" 

实际上,你不会有这个错误。

我之前也遇到过同样的问题。 我通过更改导入“调用”来解决它:

从:

import * as express from 'express';

至:

const express = require('express');

正如其他人所说,问题是您的 tsconfig.json 不适用于 server.ts。 您遗漏了设置的重要细节,这就是其他人无法复制此问题的原因。

我对问题是什么有一个很好的猜测,并且我自己也在这个相同的问题上挣扎过,我将在这里解释我的猜测,希望能帮助其他一些被这个问题折磨的可怜的灵魂。

基本问题是您的服务器代码与您的反应代码位于不同的树中。 这就是为什么 tsconfig.json 没有应用于它的原因,因为(我相信)它在指定的“./src/”路径之外。 (也许是“./website/src/”)。

您还没有向我们展示 package.json 文件,但很可能服务器条目类似于“server”:“ts-node ./website/src/server.ts”

要验证 tsconfig.json 应用程序是问题,请从命令行尝试此操作...

$ ts-node -O '{\"module\":\"commonjs\"}' ./website/src/server.ts

很有可能,事情会开始奏效。 现在解决方案可能就像添加 tsconfig.json 包含的另一个路径一样简单。

所以我在 github 上看到了这篇文章,其中基本上有两种工作方法,因为您使用的是针对 es6 add 的捆绑工具

"allowSyntheticDefaultImports": true”compilerOptions” "allowSyntheticDefaultImports": true

或者换

import express from "express";

import express = require('express');

如果您的tsconfig.json不在项目的根目录下,则可能会发生这种情况。 将 webpack 配置为指向您的目标配置文件(您可以使用变量对其进行更改以指向 dev 和 prod 配置)。

https://github.com/TypeStrong/ts-loader

如果设置,将使用给定的绝对路径作为基本路径解析 TypeScript 配置文件。 默认情况下,配置文件的目录用作基本路径。 配置文件中的相对路径在解析时相对于基本路径进行解析。 选项上下文允许将选项 configFile 设置为项目根目录以外的路径(例如 NPM 包),而 ts-loader 的基本路径可以保留为项目根目录。

尝试修改您的webpack.config.js文件以具有以下内容:

module.exports = {
  ...
  module: {
    rules: [
      {
        options: {
          configFile: path.join(__dirname, "tsconfig.json")
        }
      }
    ]
  }
};

暂无
暂无

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

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