Я получил пример проекта, следуя официальной документации React & Webpack .
Внесите следующие изменения:
Переименуйте webpack.config.tsx
webpack.config.js
(он запускается узлом, а не TypeScript)
Установите ts-loader
для переноса файлов .ts / .tsx: npm install --save-dev ts-loader
Редактирование webpack.config.js
и настройка ts-loader
Этот пример также включает babel-loader
.
Обратите внимание на строки exclude: /node_modules/,
и configFile: path.resolve('./tsconfig.json'),
, они важны и необходимы для правильной работы (подробности см. в разделе по устранению неполадок ниже)
// webpack.config.js
{
//...
module: {
rules: [
{
test: /\.(js|jsx|tsx|ts)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
{
loader: 'ts-loader',
options: {
configFile: path.resolve('./tsconfig.json'),
},
},
],
}
]
}
}
Редактировать
tsconfig.json
и добавить следующие настройки:
// tsconfig.json
{
"compilerOptions": {
//...
// Can use to "react" if you aren't using `babel-loader` and `@babel/preset-react` to handle jsx
"jsx": "react" /* Specify JSX code generation: "preserve", "react-native", or "react". */,
// Include these so the `react` imports work nicely:
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
Надеемся, что вы сможете построить проект на этом этапе:
npx webpack
$ npx webpack
Hash: 184cde71516bcbc08144
Version: webpack 4.41.5
Time: 2558ms
Built at: 01/13/2020 2:34:08 PM
Asset Size Chunks Chunk Names
bundle.js 128 KiB 0 [emitted] main
Entrypoint main = bundle.js
[2] ./src/index.tsx 498 bytes {0} [built]
[8] ./src/Main.tsx 385 bytes {0} [built]
+ 7 hidden modules
2. Файлы примеров
Вот содержимое файла для моего тестового проекта:
package. json
{
"devDependencies": {
"@babel/core": "^7.8.0",
"babel-loader": "^8.0.6",
"ts-loader": "^6.2.1",
"typescript": "^3.7.4",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
},
"dependencies": {
"@types/react": "^16.9.17",
"@types/react-dom": "^16.9.4",
"react": "^16.12.0",
"react-dom": "^16.12.0"
}
}
tsconfig. json
{
"compilerOptions": {
"target": "ES2018" /* Specify ECMAScript target version: "ES3" (default), "ES5", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019" or "ESNEXT". */,
"module": "commonjs" /* Specify module code generation: "none", "commonjs", "amd", "system", "umd", "es2015", or "ESNext". */,
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": false /* Raise error on expressions and declarations with an implied "any" type. */,
"moduleResolution": "node" /* Specify module resolution strategy: "node" (Node.js) or "classic" (TypeScript pre-1.6). */,
"baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
"forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
"jsx": "react" /* Specify JSX code generation: "preserve", "react-native", or "react". */,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
webpack.config. json
const path = require('path');
module.exports = {
entry: path.join(__dirname, './src/index.tsx'),
mode: 'production',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './dist/scripts')
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
},
module: {
rules: [
{
test: /\.(js|jsx|tsx|ts)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
},
{
loader: 'ts-loader',
options: {
configFile: path.resolve('./tsconfig.json'),
},
},
],
}
]
}
};
src / index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import Main from './Main';
ReactDOM.render( <Main />, document.getElementById('root') );
src / Main.tsx
import React from 'react';
import ReactDOM from 'react-dom';
export default function Main(){
return (<h1>This is Main</h1>);
}
3. Устранение неполадок
Я столкнулся с этими проблемами при настройке - вот решения, которые я нашел.
Ошибка: Вы получаете сообщение об ошибке: The 'files' list in config file 'tsconfig.json' is empty.
например
ERROR in [tsl] ERROR
TS18002: The 'files' list in config file 'tsconfig.json' is empty.
ERROR in ./src/index.tsx
Module build failed (from ./node_modules/ts-loader/index.js):
Error: error while parsing tsconfig.json
Решение: разрешить полный tsconfig.json
путь
// webpack.config.js
{
loader: 'ts-loader',
options: {
// configFile: './tsconfig.json', // !! WRONG
configFile: path.resolve('./tsconfig.json'), // CORRECT
},
}
Ошибка: Вы получаете ошибка типа: Module not found: Error: Can't resolve '...' in 'path-to-project/node_modules/react'
например,
ERROR in ./node_modules/react/index.js
Module not found: Error: Can't resolve './Main' in 'C:\webpack-typescript\node_modules\react'
@ ./node_modules/react/index.js 15:31-48
@ ./src/index.tsx
Решение: Убедитесь, что вы исключаете node_modules
из правила ts-loader
.
// webpack.config.js
{
module: {
rules: [
{
test: /\.(js|jsx|tsx|ts)$/,
exclude: /node_modules/, // <--- make sure this is here!
// ...
}
]
}
}