webpack - "ไม่พบโมดูล" เมื่อใช้ raw-loader และ TypeScript
ฉันกำลังพยายามที่จะรวม vertex และ fragment shaders ของ WebGL บางส่วนโดยการ import พวกมันเป็นสตริง
ฉันมีโครงสร้างโครงการแบบนี้:
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;
}
Fu.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 ควรเพียงพอที่จะแก้ปัญหานี้ แต่กลับไม่เป็นเช่นนั้น—และฉันก็ไม่รู้ด้วยซ้ำว่าจะหาสาเหตุอย่างไร
เกิดอะไรขึ้น? ฉันต้องทำอะไรบ้างเพื่อที่จะนำเข้าฟายล์ดิบใน Webpack ด้วย TypeScript? (หรืออย่างน้อยที่สุด ฉันสามารถทำอะไรได้บ้างเพื่อตรวจหาว่าทำไมถึงหาไฟล์นี้ไม่เจอ?)
คำตอบ #1
ในกรณีของฉันกับ Next.js (รวมถึง Typescript) ฉันแก้ปัญหานี้โดยการติดตั้ง raw-loader เท่านั้น จริงๆ นะ
npm install raw-loader
ปรากฏว่า raw-loader ไม่ได้มาพร้อมกับโครงการ Next.js ของฉัน ฉันเป็นมือใหม่ ดังนั้นฉัน สมมติ ว่ามันมาพร้อมกับโครงการของฉัน
ดังนั้นสำหรับใครก็ตามที่พบปัญหาเดียวกัน ให้ตรวจสอบไฟล์ package.json ของคุณเพื่อดูว่า raw-loader มีอยู่หรือไม่ ก่อนลองวิธีแก้ปัญหาอื่น ๆ
คำตอบ #2
ในกรณีการทำซ้ำเฉพาะนี้ ฉันเผลอลบ "./" ออกจากการนำเข้าใน Foo.ts มันควรอ่านว่า:
import stuff from './shad/foo.frg'
ปัญหาจริงที่ทำให้เกิดคำถามนี้ ฉันได้จำกัดลงไปที่ข้อบกพร่องที่เห็นได้ชัดเกี่ยวกับการอ้างอิงโครงการใน raw-loader
