使用raw-loader和TypeScript时出现“找不到模块”的错误。

6
我正在尝试通过将WebGL顶点和片段着色器作为字符串进行导入来包含它们。
我的项目结构如下:
myproj/
  src/
    shad/
      foo.frg
      foo.vtx
    shad.d.ts
    Foo.ts
  dist/
    ...
  built/
    ...
  tsconfig.json
  package.json
  webpack.config.js

shad.d.ts

declare module '*.vtx' {
    const content: string;
    export default content;
}

declare module '*.frg' {
    const content: string;
    export default content;
}

Foo.ts

import stuff from 'shad/foo.frg'

console.log(stuff)

tsconfig.json

{
    "include": [
        "src/**/*", 
        "src/shad/**/*.vtx", 
        "src/shad/**/*.frg",
    ], 
    "exclude": ["node_modules"],
    "compilerOptions": {
        "target": "ES2018",
        "module": "es2015",
        "declaration": true,
        "sourceMap": true,
        "outDir": "built",
        "composite": true,
        "strict": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true
    }
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: {
    test: './src/Foo.ts',
  },
  mode:    'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  },
  module: {
    rules: [
      {
        test:    /\.tsx?$/,
        use:     'ts-loader',
        exclude: [
          /node_modules/,
        ]
      },
      {
        test: /\.(vtx|frg)$/i,
        use:  'raw-loader',
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js', '.vtx', '.frg' ],
  },
  output: {
    filename: '[name].bundle.js',
    path:      path.resolve(__dirname, 'dist'),
  },
};

当我运行npx webpack时,我得到:

ERROR in ./src/Foo.ts
Module not found: Error: Can't resolve 'shad/foo.frg' in '/Users/tbabb/test/tmp/tsproj/src'
 @ ./src/Foo.ts 1:0-33 4:16-21

此外,src/shad/文件夹及其内容在built/目录中不存在。
我已经查看了TypeScript和Webpack的所有文档,以及这里的许多其他答案。根据我所读的大部分内容,shad.d.ts的存在和内容足以解决这个问题,但事实并非如此,我甚至不知道该如何弄清原因。
发生了什么?我必须怎样在TypeScript中使用Webpack导入原始文件?(或者至少,我可以做些什么来找出为什么找不到它?)
3个回答

7
在我的情况下,我使用Next.js(还有Typescript),只需安装raw-loader就可以解决这个问题。
npm install raw-loader

原来我的Next.js项目中没有raw-loader。因为我是新手,所以我假设它已经包含在我的项目中。

所以,如果有其他人遇到同样的问题,请在尝试其他解决方案之前检查您的package.json文件,看看是否完全存在raw-loader。

raw-loader dependency


0
在这个特定的复现案例中,我不小心在Foo.ts的导入中省略了"./"。应该这样写:
import stuff from './shad/foo.frg'

导致我提出这个问题的实际问题是,我已经缩小到raw-loader中项目引用的明显错误


-1
将文件shad.d.ts重命名为global.d.ts并移动到源目录的根目录(就在index.ts旁边)。这样,TypeScript编译器就能够正确地识别它了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接