Webpack не может найти импорт, который TypeScript (по-видимому) находит - PullRequest
0 голосов
/ 02 декабря 2018

Справочная информация: я начал с (работает нормально для меня) Пример ядра ASP.NET для SignalR и веб-пакета .Моя цель - использовать эту библиотеку TypeScript для выполнения клиентской интерполяции для многопользовательской игры, которая является авторитетной на стороне сервера.

Причина, по которой я думаю, что проблема связана с веб-пакетом, заключается в том, что VisualStudio имеетintellisense для библиотеки box2d.ts и tsc не сообщают об ошибках при запуске самостоятельно.

Это мой первый проект с webpack и TypeScript, поэтому извиняюсь, если я пропустил что-то очевидное.

Ошибка, сообщенная веб-пакетом:

ERROR in ./src/index.ts
Module not found: Error: Can't resolve 'Box2D' in 
'C:\Users\nathan.b\Desktop\Gamey\Gamey\src'
 @ ./src/index.ts 2:0-31 3:14-26

ОБНОВЛЕНИЕ: Ошибка с подробным выводом:

ERROR in ./src/index.ts
Module not found: Error: Can't resolve 'Box2D' in 'C:\Users\nathan.b\Desktop\Gamey\Gamey\src'
resolve 'Box2D' in 'C:\Users\nathan.b\Desktop\Gamey\Gamey\src'
  Parsed request is a module
  using description file: C:\Users\nathan.b\Desktop\Gamey\Gamey\package.json (relative path: ./src)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      C:\Users\nathan.b\Desktop\Gamey\Gamey\src\src doesn't exist or is not a directory
      C:\Users\nathan.b\Desktop\Gamey\Gamey\src\node_modules doesn't exist or is not a directory
      C:\Users\nathan.b\Desktop\Gamey\src doesn't exist or is not a directory
      C:\Users\nathan.b\Desktop\Gamey\node_modules doesn't exist or is not a directory
      C:\Users\nathan.b\Desktop\src doesn't exist or is not a directory
      C:\Users\nathan.b\Desktop\node_modules doesn't exist or is not a directory
      C:\Users\nathan.b\src doesn't exist or is not a directory
      C:\Users\nathan.b\node_modules doesn't exist or is not a directory
      C:\Users\src doesn't exist or is not a directory
      C:\Users\node_modules doesn't exist or is not a directory
      C:\src doesn't exist or is not a directory
      C:\node_modules doesn't exist or is not a directory
      looking for modules in C:\Users\nathan.b\Desktop\Gamey\Gamey\src
        using description file: C:\Users\nathan.b\Desktop\Gamey\Gamey\package.json (relative path: ./src)
          Field 'browser' doesn't contain a valid alias configuration
      looking for modules in C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules
        using description file: C:\Users\nathan.b\Desktop\Gamey\Gamey\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: C:\Users\nathan.b\Desktop\Gamey\Gamey\package.json (relative path: ./src/Box2D)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
          using description file: C:\Users\nathan.b\Desktop\Gamey\Gamey\package.json (relative path: ./node_modules/Box2D)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D is not a file
            .js
              Field 'browser' doesn't contain a valid alias configuration
              C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules\Box2D doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D.js doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules\Box2D.js doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D.ts doesn't exist
              C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules\Box2D.ts doesn't exist
            as directory
              C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules\Box2D doesn't exist
            as directory
              existing directory
                using path: C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D\index
                  using description file: C:\Users\nathan.b\Desktop\Gamey\Gamey\package.json (relative path: ./src/Box2D/index)
                    no extension
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D\index doesn't exist
                    .js
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D\index.js doesn't exist
                    .ts
                      Field 'browser' doesn't contain a valid alias configuration
                      C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D\index.ts doesn't exist
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\src]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\node_modules]
[C:\Users\nathan.b\Desktop\Gamey\src]
[C:\Users\nathan.b\Desktop\Gamey\node_modules]
[C:\Users\nathan.b\Desktop\src]
[C:\Users\nathan.b\Desktop\node_modules]
[C:\Users\nathan.b\src]
[C:\Users\nathan.b\node_modules]
[C:\Users\src]
[C:\Users\node_modules]
[C:\src]
[C:\node_modules]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules\Box2D]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D.js]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules\Box2D.js]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D.ts]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\node_modules\Box2D.ts]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D\index]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D\index.js]
[C:\Users\nathan.b\Desktop\Gamey\Gamey\src\Box2D\index.ts]
 @ ./src/index.ts 2:0-31 3:14-26

index.ts:
Достаточно, чтобы убедиться, что ничего не скомпилировано.

import * as signalR from "@aspnet/signalr";
import * as box2d from "Box2D";

const g: box2d.b2Vec2 = new box2d.b2Vec2(0, -10)
console.log(g);

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/hub")
    .build();

tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "Box2D": [ "./Box2D/Box2D" ]
    }
  }
}

webpack.config.js:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    entry: "./src/index.ts",
    output: {
        path: path.resolve(__dirname, "wwwroot"),
        filename: "[name].[chunkhash].js",
        publicPath: "/"
    },
    resolve: {
        extensions: [".js", ".ts"]
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: "ts-loader"
            },
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, "css-loader"]
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin(["wwwroot/*"]),
        new HtmlWebpackPlugin({
            template: "./src/index.html"
        }),
        new MiniCssExtractPlugin({
            filename: "css/[name].[chunkhash].css"
        })
    ]
};

Структура проекта: Project structure

Ответы [ 2 ]

0 голосов
/ 03 декабря 2018

После считывания разрешения модуля веб-пакета , другое решение состоит в том, чтобы переключиться с ссылок на модули либо на абсолютные, либо на относительные ссылки на пути.

Изменения:
tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "moduleResolution": "node",
    "baseUrl": "..",
    "paths": {
      "Box2D": [ "./src/Box2D/Box2D" ]
    }
  }
}

webpack.config.js:
Оставьте то же, что и в вопросе - никаких изменений не требуется.

index.ts:

import * as box2d from "./Box2D/Box2D";
0 голосов
/ 02 декабря 2018

Так что я наконец-то заработал.Я должен был явно указать путь к библиотеке Box2D.Ни один глобальный вариант не сработал (/ * или ** / *), но, возможно, я чего-то там упускаю.

Изменение:

resolve: {
    modules: ['./src/Box2D', 'node_modules'],
    extensions: [".js", ".ts"]
},
...