Managing dependencies and automating setup processes can be tricky when incorporating Typescript into a

Query:

How can I easily set up Typescript with Symfony without making extensive changes to Symphony's configuration files?

Here are the key requirements for the solution:

  1. Typescript MVC Pattern should be set up in a private typescript directory:

    src > XBundle > Resources > private > typescript

  2. Javascript bundles should be compiled in :

    src > XBundle > Resources > public > js

  3. The private directory should contain multiple apps for various pages. Each app can have its own tsconfig.json file if needed.

  4. An app can consist of files like home.app.ts importing search.component.ts and chat.component.ts

  5. Compiled "apps" should be stored in the public > js directory mentioned above and named, for example, home.bundle.js

  6. Only x.bundle.js files should be present in the public > js folder

  7. The bundles should be added to twig files, and the view should run the bundle without the need for an extra script to call the "module". This is to avoid using AMD or System

What I Don't Want:

I am not interested in solutions involving react or angular, and prefer a general approach using the /web directory or the Resources directory in a bundle within a Symfony project.

Most articles on this topic focus on symfony2 and attempt to integrate react and angular.

I do not need a step-by-step installation guide for npm and tsc.

An automatic compile feature is not necessary as Phpstorm already handles it automatically for me.

Answer №1

Shoutout to @zerkms for the guidance on using webpack to make this work. Still a work in progress, room for further optimization.

Setup:

  1. Get webpack installed, I opted for a global installation. (Not sure how to set up Phpstorm to utilize webpack as there doesn't seem to be a built-in system for it)
  2. Navigate to

    src > XBundle > Resources > private > typescript

  3. npm init -y

  4. Install the dev dependencies:
    npm install --save-dev awesome-typescript-loader
    and
    npm install --save-dev typescript

Note:

@Morgan Touverey Quilling suggests installing webpack locally, up to you:

npm install --save-dev webpack

Configuration:

Check out my folder structure:

├── XBundle/
│   ├── Controller
│   ├── Resources
│   │   ├── config
│   │   ├── private
│   │   │   ├── typescript
│   │   │   │   ├── components
│   │   │   │   │   ├── auth
│   │   │   │   │   │   ├── auth.component.ts
│   │   │   │   │   ├── search
│   │   │   │   │   │   ├── search.component.ts
│   │   │   │   ├── services
│   │   │   │   │   ├── http.service.ts
│   │   │   │   ├── node_modules
│   │   │   │   ├── package.json
│   │   │   │   ├── webpack.config.js
│   │   │   │   ├── tsconfig.json
│   │   ├── public
│   │   │   ├── js
│   │   │   │   ├── build
│   │   │   │   │   ├── auth.bundle.js

webpack.config.js This config could probably be simplified much further.

Create a new config for each bundle, pointing to the main file. Remember to rename the output bundle.

Stick to one bundle per page. If you need different bundles (like auth.bundle.js and search.bundle.js) on the home page, consider creating a home.component.ts using auth.component.ts and search.component.ts, then adjust webpack.config.js to create home.bundle.js

const path = require('path');

//Common configurations
let config = {
    module: {
        loaders: [
            { test: /\.ts$/, loader: 'awesome-typescript-loader' }
        ]
    },
    resolve: {
        extensions: ['.ts']
    }
};

//Repeat this for each bundle needed
let authConfig = Object.assign({}, config, {
    entry: path.join(__dirname, 'components/auth','auth.component.ts'),
    output: {
        path: path.join(__dirname, '../../public/js/build'),
        filename: 'auth.bundle.js',
        library: 'XApp'
    }
});

//Include each config here.
module.exports = [
    authConfig
];

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "sourceMap": true,
    "moduleResolution": "node",
    "lib": ["dom", "es2015", "es2016"]
  },
  "exclude": [
    "node_modules"
  ]
}

Execution

Run webpack in the directory where webpack.config.js is located.

Adding JS to your Twig file

Add this in one of your templates.

{% block javascripts %}
    {# More stuff here #}
    {% javascripts
    '@XBundle/Resources/public/js/build/auth.bundle.js'
    %}
    {# More stuff here #}
    {% endjavascripts %}
{% endblock %}

For any new bundles.js created for the first time, run these commands in the root directory of your Symfony project:

php bin/console assets:install
php bin/console assetic:dump

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The deployment on Vercel for a Node Express and TypeScript project is experiencing issues with building

After uploading my project with node using express + typescript, I encountered a problem. The app generates a folder called dist for building, but when vercel deployed my app, it didn't run the build command. To resolve this issue, I had to manually b ...

"Exploring the methods to retrieve Firebase authentication error details and outputting the console log message along with

When I encounter an error in Firebase authentication, I want to display it in the console log. However, nothing is being logged and the catch block is not even getting executed. I am unsure about why this is happening and how to retrieve the error code and ...

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...

It appears that Typescript mistakenly interprets a class or type as a value, indicating that "'Classname' is being referred to as a value but used as a type here."

I want to pass an Object of a React.Component as "this" to a Child React.Component in the following way: component 1 file: class Comp1 extends React.Component<...,...> { ... render() { return (<Comp2 comp1={this}/> ...

Steps to retrieve the value stored in a variable within an Angular service from a separate component

How can I effectively share question details and an array of options from one component to another using services? What is the recommended method for storing and retrieving these values from the service? In my question-service class: private static ques ...

What is the process for downloading a .docx file encoded in Base64?

Trying to download a .docx file received from the backend. The object being received is shown below: https://i.sstatic.net/nHKpn.png Download attempt using the following code: const blob = new Blob([fileSource.FileData], { type: fileSource.FileType }); ...

The path referenced in typings is incorrect

I am currently facing an issue with my Typescript library that I am trying to publish on npmjs. It seems like the types file is not being exported correctly. The library has a simple method in the src/index.ts file and typings from src/typings/index.d.ts. ...

Issue encountered while importing TypeScript files from an external module in a Next.js project

Encountering an issue within my Next.js project with the following project structure: ├── modules/ │ └── auth/ │ ├── index.ts │ ├── page.tsx │ └── package.json └── nextjs-project/ ├─ ...

The type 'FileUpload[][]' cannot be assigned to the type 'AngularFireList<FileUpload[]>'

I'm currently working on an Angular application integrated with Firebase for the purpose of uploading images to the database and retrieving them as well. upload-file.service.ts import {Injectable} from '@angular/core'; import {AngularFireD ...

The source code in VS Code was not accurately linked

I'm currently facing an issue with running my angular2 project from vs code. Below are the contents of my tsconfig and launch.json files. tsconfig.json { "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experi ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

Is it possible to use the Optimistic Hook with boolean values?

I am facing an issue with a switch component where the checked value is updated only after refetching the data when the user is changed to an admin status. Currently, there is a delay when clicking the switch as it takes time to load and then updates. It ...

Loading an index.html file using Webpack 3, Typescript, and the file-loader: A step-by-step guide

Attempting to utilize the file-loader and Webpack 3 to load my index.html file is proving to be a challenge. The configuration in my webpack.config.ts file appears as follows: import * as webpack from 'webpack'; const config: webpack.Configura ...

"Error: The property $notify is not found in the type" - Unable to utilize an npm package in Vue application

Currently integrating this npm package for notification functionalities in my Vue application. Despite following the setup instructions and adding necessary implementations in the main.ts, encountering an error message when attempting to utilize its featur ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

"Utilize Typescript to dynamically check data types during runtime and receive alerts for any potential

INTRODUCTION I am currently working with Angular 6. In Angular, typescript is utilized to allow you to specify the data type of your function's arguments: public fun1(aaa: number) { console.log(aaa); } If I attempt to call fun1 with a parameter ...

Enhance Express Middleware with Typescript for advanced functionality

Currently in the process of developing a REST API using Express and Typescript, I am encountering difficulties when trying to extend the Request/Response objects of Express. Although my IDE shows no errors, Typescript throws TS2339 Errors during compilati ...

What is the best way to modify an object within a pure function in JavaScript?

Currently, I am exploring different strategies to ensure that a function remains pure while depending on object updates. Would creating a deep copy be the only solution? I understand that questions regarding object copying are quite common here. However, ...

Can you point me to the source of definition for Vue 2's ComponentDefinition and ComponentConstructor types?

I am struggling to add a dynamic Vue 2 component with correct typing in TypeScript. The documentation clearly mentions that the is attribute accepts values of type string | ComponentDefinition | ComponentConstructor, but I cannot locate these custom types ...

Obtain the hexadecimal color code based on the MUI palette color name

Is there a way to extract a hexcode or any color code from a palette color name in Material UI? Here is my use case: I have a customized Badge that I want to be able to modify just like the normal badges using the color property. The component code looks ...