ERROR in Must have a source file to refactor

3.9k Views Asked by At

Strange error with webpack compilation:

ERROR in Must have a source file to refactor.

Looking at the source code I found this message in ./node_modules/@ngtools/refactor.js:

...   
if (!sourceFile) {
  throw new Error('Must have a source file to refactor.');
}

The configuration of @ngtools webpack plugin is pretty straightforward:

  {
    test: /\.ts$/,
    use: '@ngtools/webpack',
  } 
3

There are 3 best solutions below

0
On

For anyone in pain, attempting to find this solution; merely change:

new AngularCompilerPlugin({
      mainPath: 'src/main.ts',<----
      tsConfigPath: 'src/tsconfig.app.json',
      skipCodeGeneration: true
    }),

..to this:

new AngularCompilerPlugin({
      mainPath: 'main.ts',<----
      tsConfigPath: 'src/tsconfig.app.json',
      skipCodeGeneration: true
    }),
0
On

Don't forget to include AngularCompilerPlugin with correct mainPath configuration in webpack.config.js. At least that's what fixed this for me.

plugins: [
  /**
   * Angular's webpack plugin to compile typescript and AOT for templates
   **/
  new ngTools.AngularCompilerPlugin({
    tsConfigPath: path.join(CONTEXT_DIR, "tsconfig.json"),
    mainPath: path.join(CONTEXT_DIR, "src/main.ts")
  }),
...
]
0
On

I received this error while running "ng build --aot=true" on an angular library. The reason was the missing files in the build configuration in angular.json file. The project was generated as an angular application instead of a library. The build section in angular.json was pointing to src/main.ts and src/style.css but there were no such files in the project. I added missing files to resolve the issue. Alternatively configuration can be changed to a library project.

"build": {
  "builder": "@angular-devkit/build-angular:browser",
  "options": {
    "outputPath": "dist/ui-common",
    "index": "src/index.html",
    "main": "src/main.ts", //missing file