【问题标题】:"Cannot find module" when using raw-loader and TypeScript使用 raw-loader 和 TypeScript 时“找不到模块”
【发布时间】:2020-05-31 03:22:52
【问题描述】:

我正在尝试通过importing 将一些 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

此外,built/ 目录中没有 src/shad/ 文件夹及其内容。

我在 TypeScript 和 Webpack 的所有文档以及其他许多 answers 文档中都四处游荡。从我读过的大部分内容来看,shad.d.ts 的存在和内容应该足以解决这个问题,但它并没有——我什至不知道如何找出原因。

发生了什么事?使用 TypeScript 在 Webpack 中导入原始文件需要做什么? (或者至少,我能做些什么来弄清楚为什么没有找到它?)

【问题讨论】:

    标签: typescript webpack raw-loader


    【解决方案1】:

    在我使用 Next.js(也是 Typescript)的情况下,我通过安装 raw-loader 解决了这个问题。真的。

    npm install raw-loader
    

    原来我的 Next.js 项目没有附带 raw-loader。我是新手,所以我假设它是我的项目附带的。

    因此,对于遇到相同问题的其他人,请在尝试其他解决方案之前检查您的 package.json 文件以查看 raw-loader 是否存在。

    【讨论】:

      【解决方案2】:

      在这个特殊的复制案例中,我不小心在Foo.ts 的导入中省略了“./”。它应该是:

      import stuff from './shad/foo.frg'
      

      引发这个问题的实际问题我已经缩小到an apparent bug,项目引用在raw-loader

      【讨论】:

        【解决方案3】:

        将文件 shad.d.ts 重命名为 global.d.ts 并移至源目录的根目录(紧邻 index.ts )。这让 typescript 编译器为我挑选它。

        【讨论】:

          猜你喜欢
          • 2020-02-06
          • 1970-01-01
          • 2016-01-20
          • 2021-08-16
          • 2020-01-29
          • 2017-11-01
          • 2019-05-17
          • 2019-08-16
          • 2016-09-20
          相关资源
          最近更新 更多