Laravel 5.6集成TypeScript遇npm run dev报错,求排查配置问题
Hey there, let’s figure out why your npm run dev is throwing errors when setting up TypeScript in Laravel 5.6. After checking your config files, I’ve spotted a few key issues that are likely causing the problem:
1. Trailing Comma in tsconfig.json
JSON doesn’t allow trailing commas after the last property in an object, but your tsconfig.json has one after "strict": true,. This will cause TypeScript to fail parsing the config file entirely.
2. Incomplete Webpack Resolve Extensions
Your resolve.extensions only includes .ts, but Webpack and Laravel Mix need to resolve other common file types like .js and .json too. Missing these can break module resolution for dependencies or internal Laravel assets.
3. Unoptimized ts-loader Rule
Not excluding node_modules from the ts-loader rule can lead to unnecessary (and failed) compilation of third-party code, which might trigger unexpected errors.
Fixed Configuration Files
Let’s update your configs to fix these issues:
Corrected tsconfig.json
{ "compilerOptions": { "target": "es5", "module": "commonjs", "strict": true }, "include": [ "resources/assets/ts/**/*.ts" ], "exclude": [ "node_modules" ] }
Corrected webpack.mix.js
let mix = require('laravel-mix'); mix.webpackConfig({ resolve: { extensions: ['.ts', '.js', '.json'] // Add essential file extensions for proper module resolution }, module: { rules: [ { test: /\.ts$/, loader: 'ts-loader', exclude: /node_modules/ // Skip compiling third-party code to avoid conflicts } ] } }); mix.js('resources/assets/ts/app.ts', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css');
Additional Steps to Fix the Error
Install Required Dependencies
Make sure you’ve installedtypescriptandts-loader(they’re not included with Laravel Mix by default):npm install typescript ts-loader --save-devClear Cache and Rebuild
Old cached assets can cause unexpected errors. Delete the compiled files inpublic/js/then run:npm run devIf issues persist, try clearing the npm cache with
npm cache clean --forceand reinstalling dependencies withnpm install.Check Strict Mode Compliance
Since you have"strict": truein your tsconfig, your TypeScript code must follow strict type rules (no implicitanytypes, all variables need explicit types, etc.). If you’re just getting started, you can temporarily set"strict": falseto verify compilation works, then gradually enable strict checks as you refine your code.
内容的提问来源于stack exchange,提问作者Simpdad

