symfony / webpack-encore

A simple but powerful API for processing & compiling assets built around Webpack
https://symfony.com/doc/current/frontend.html
MIT License
2.23k stars 198 forks source link

Webpack with typescript breaks the watcher #1013

Open lebadapetru opened 3 years ago

lebadapetru commented 3 years ago

I decided to add ts into my working symfony+vue project and so i configured it and ran npm run watch which builded successfully, but when i change anything in any .vue or .ts files, the watcher breaks with the following error:

[webpack-cli] Error: The loaded module contains errors
    at /Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/dependencies/LoaderPlugin.js:110:11
    at /Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/Compilation.js:1665:8
    at /Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/util/AsyncQueue.js:352:5
    at Hook.eval [as callAsync] (eval at create (/Users/lebadapetrudecebal/Projects/erp/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at AsyncQueue._handleResult (/Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/util/AsyncQueue.js:322:21)
    at /Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/util/AsyncQueue.js:305:11
    at /Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/Compilation.js:1337:15
    at /Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/HookWebpackError.js:69:3
    at Hook.eval [as callAsync] (eval at create (/Users/lebadapetrudecebal/Projects/erp/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
    at Cache.store (/Users/lebadapetrudecebal/Projects/erp/node_modules/webpack/lib/Cache.js:107:20)

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ],
    "baseUrl": ".",
    "paths": {
      "resources/*": [
        "resources/*"
      ]
    }
  },
  "include": [
    "resources/**/*.ts",
    "resources/**/*.tsx",
    "resources/**/*.vue",
  ],
  "exclude": [
    "node_modules"
  ]
}

webpack.config.js:

const Encore = require('@symfony/webpack-encore');
const path = require('path');
const webpack = require('webpack');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
  Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
  // directory where compiled assets will be stored
  .setOutputPath('public/build/')
  // public path used by the web server to access the output path
  .setPublicPath('/build')
  // only needed for CDN's or sub-directory deploy
  //.setManifestKeyPrefix('build/')
  .copyFiles({
    from: './resources/assets/media',
    to: 'media/[path][name].[ext]',
    pattern: /\.(png|jpg|jpeg|svg)$/
  })
  .copyFiles({
    from: './resources/assets/fonts',
    to: 'fonts/[path][name].[ext]',
    pattern: /\.(ttf)$/
  })
  /*
   * ENTRY CONFIG
   *
   * Add 1 entry for each "page" of your app
   * (including one that's included on every page - e.g. "app")
   *
   * Each entry will result in one JavaScript file (e.g. main.js)
   * and one CSS file (e.g. app.css) if you JavaScript imports CSS.
   */
  .addEntry('main', './resources/main.js')
  //.addEntry('page1', './assets/js/page1.js')
  //.addEntry('page2', './assets/js/page2.js')

  // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
  .splitEntryChunks()

  // will require an extra script tag for runtime.js
  // but, you probably want this, unless you're building a single-page app
  .enableSingleRuntimeChunk()

  /*
   * FEATURE CONFIG
   *
   * Enable & configure other features below. For a full
   * list of features, see:
   * https://symfony.com/doc/current/frontend.html#adding-more-features
   */
  .cleanupOutputBeforeBuild()
  .enableBuildNotifications()
  .enableSourceMaps(!Encore.isProduction())
  // enables hashed filenames (e.g. app.abc123.css)
  .enableVersioning(Encore.isProduction())

  // enables @babel/preset-env polyfills
  .configureBabel(() => {
  }, {
    useBuiltIns: 'usage',
    corejs: 3
  })

  // enables Sass/SCSS support
  .enableSassLoader()

  // enables Vue support
  .enableVueLoader(() => {
  }, {
    version: 3,
    runtimeCompilerBuild: false //if using only single file components, this is not needed (https://symfony.com/doc/current/frontend/encore/vuejs.html#runtime-compiler-build)

  })
  // uncomment if you use TypeScript
  .enableTypeScriptLoader()

  // uncomment if you're having problems with a jQuery plugin
  .autoProvidejQuery()
  .addAliases({
    'resources': path.resolve('./resources')
  })

  /*.addPlugin(
    new webpack.DefinePlugin({
      // Drop Options API from bundle
      __VUE_OPTIONS_API__: false,
      __VUE_PROD_DEVTOOLS__: false
    })
  )*/

// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes()

// uncomment if you use API Platform Admin (composer req api-admin)
//.enableReactPreset()
//.addEntry('admin', './assets/js/admin.js')
;

module.exports = Encore.getWebpackConfig();

It might be something i've missed while configuring it, but since the error doesn't tell me anything...it's hard to figure it out.

weaverryan commented 3 years ago

Hi there!

yea, that’s a deep error from Webpack itself :/. I’m sorry to say that, at first glance, I also don’t have any ideas - I know Webpack pretty well, but that stacktrace doesn’t contain any hints. Otherwise, though I don’t have much personal experience with a typescript + vue setup, your config looks boring (in a good way)

lebadapetru commented 3 years ago

I upgraded the webpack to 1.5.0 but this problem still persist. I managed to find a similar issue here .

When i run npm run watch it compiles without any error, but if i change anything it throws a list of errors in the .ts files that i have imported in the .vue components. The errors do not make any sense though:

 error  in /Users/lebadapetrudecebal/Projects/erp/resources/ts/helpers.ts                                                                                         5:11:46 PM

[tsl] ERROR in /Users/lebadapetrudecebal/Projects/erp/resources/ts/helpers.ts(2,8)
      TS2339: Property '__file' does not exist on type '{}'.

 error  in /Users/lebadapetrudecebal/Projects/erp/resources/views/products/components/lists/TableView.vue.ts                                                      5:11:46 PM

[tsl] ERROR in /Users/lebadapetrudecebal/Projects/erp/resources/views/products/components/lists/TableView.vue.ts(5,10)
      TS2614: Module '"resources/ts/helpers"' has no exported member 'setImageSize'. Did you mean to use 'import setImageSize from "resources/ts/helpers"' instead?

 error  in /Users/lebadapetrudecebal/Projects/erp/resources/views/products/components/lists/TableView.vue.ts                                                      5:11:46 PM

[tsl] ERROR in /Users/lebadapetrudecebal/Projects/erp/resources/views/products/components/lists/TableView.vue.ts(5,24)
      TS2614: Module '"resources/ts/helpers"' has no exported member 'getImagePlaceholderPath'. Did you mean to use 'import getImagePlaceholderPath from "resources/ts/helpers"' instead?

helpers.ts:

export const setImageSize = (url: string, width? : number, height?: number): string => {
  return url.replace("{widthxheight}", `${width ? width : 150}x${height ? height : ''}`)
}

export const getImagePlaceholderPath = (): string => {
  return '/build/media/default-image.jpg'
}

Also, if i go to the helpers.ts AND pagination.ts where those errors are and i simply add a blank space to each file, the watcher compiles them succesfully....

jerrebm commented 2 years ago

@lebadapetru did you ever find a solution? Running into a similar issue...

lebadapetru commented 2 years ago

@egyptik , my problem was quite a stupid one...

.addEntry('main', './resources/main.js') i kept the old .js main file instead of replacing it with a .ts file as someone figured out here

Did this fix it for you?

bigwhoop commented 12 months ago

I wanted to confirm that replacing the (in my case) app.js with app.ts solved it.

  1. Rename app.js to app.ts
  2. Replace .addEntry('app', './assets/app.js') with .addEntry('app', './assets/app.ts') in webpack.config.js
carsonbot commented 1 month ago

Thank you for this issue. There has not been a lot of activity here for a while. Has this been resolved?