javascript - Bagaimana cara hanya mengompilasi satu file typescript dengan webpack 5 dan mengecualikan semuanya?
Saya memiliki runtime Node.js yang sedang menjalankan aplikasi React.
sumber lengkap dapat ditemukan di sini, berikut adalah struktur foldernya:
Saya menjalankan npm run build dari dalam react-app untuk mengompilasi aplikasi react itu sendiri.
Lalu saya ingin menjalankan npm run build dari root proyek untuk mengompilasi HANYA file index.ts ke /dist/index.js, dan MENGABAIKAN file-file di folder react-app.
Berikut adalah webpack.config.ts saya:
const webpack = require("webpack");
const path2 = require("path");
const nodeExternals = require("webpack-node-externals");
const copyFiles = require('copy-webpack-plugin');
module.exports = {
entry: './index.ts',
target: "node",
mode: "production",
externals: [nodeExternals()],
resolve: {
extensions: ['.ts']
},
module: {
rules: [
// all files with a `.ts` extension will be handled by `ts-loader`
{ test: /index.ts$/, loader: 'ts-loader', exclude: [ path2.resolve(__dirname, 'react-app')]}
]
},
plugins: [new webpack.HotModuleReplacementPlugin(), new copyFiles({ patterns: [{ from: 'react-app/build', to: 'build'}]})],
output: {
path: path2.resolve(__dirname, 'dist'),
filename: 'index.js'
},
};
Saya sudah mencoba hanya menyertakan file index.ts dan mengecualikan folder react-app dengan berbagai cara, tapi webpack terus mencoba mengompilasi file ts di folder react-app.
Berikut adalah package.json saya:
{
"name": "frontend-service",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node dist/index.js",
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.11",
"@types/node": "^14.14.31",
"copy-webpack-plugin": "^7.0.0",
"ts-loader": "^8.0.17",
"ts-node": "^9.1.1",
"typescript": "^4.2.2",
"webpack": "^5.24.2",
"webpack-cli": "^4.5.0",
"webpack-node-externals": "^2.5.2"
}
}
Tolong bantu.
Jawaban #1
Awalnya saya mengira komentar Keith salah karena saya menambahkan "include": ["index.ts"] ke "compileOptions" dari tsconfig saya dan mendapat:
error TS5023: Unknown compiler option 'include'.
Tapi ternyata saya harus meletakkannya di luar compileOptions seperti:
{
"compilerOptions": {
// Your options.....
},
"include": ["./index.ts"]
}
Dan itu berhasil!
Namun, proyek react tidak bisa dibangun lagi karena menemukan:
a different version of webpack-dev-server was detected higher up in the tree
Saya sarankan untuk tidak menempatkan proyek react typescript di dalam proyek node typescript. Mungkin lebih baik membuat folder utama dan menempatkan proyek react di folder yang sejajar dengan proyek node.

