From its first lines until today, the Moroccan railway network has undergone many major changes, especially during the colonial era. Much of the existing network was shaped or built during this same era.
Morocco was, at the time, colonized by different countries, i.e., France (middle) and Spain (north and south) in addition to the international status of the northern most city of Tangier. This meant that the network was built by different authorities often with different choice of technologies such as the gauge, i.e., the distance between the rails.
The first lines were built with narrow-gauge rails, meaning that was only 600 mm (smaller than the current standard gauge of 1 435 mm). Some lines were ordered to be built by the French army as early as 1912 and the network was around 1 000 km of narrow-gauge lines by the year 1915. Most of these lines go almost as the routes of the current network.
The decision to adopt standard-gauge came when the first standard-gauge lines were built around 1923. Most of these new standard gauge lines were conversions of the previously built narrow-gauge network. One reason for this standardisation was to allow trains to go between different north African countries which under the French colonisation such as Algeria and Tunisia. Another reason is to connect the railway network with the Moroccan territory which is under the Spanish control in the north.
After the effort of converting and building lines in the standard-gauge rail, the next step was the electrification to make use of the hydraulic-power resources from the Atlas Mountains.
Several issues appeared with the rolling-stock, most of the steam-engine locomotives that were used in the system were not adapted to the local geography and climate conditions. Electrification was therefore initiated as early as 1925.
The electrification process was not as successful as the standardisation of the narrow-gauge rails. Only fewer than 50% of the standard-gauge lines have been electrified. The first section was electrified and put in operation around 1927 in the region of Casablanca. The line used a DC with 3kV.
The Moroccan Railways Company was formed in 1922 to take over all the routes that were built by the military. The company controlled all the standard-gauge lines in the country, except between Fez and Tangiers. The latter is owned by the Tangiers-Fez Railway (60% by French and 40% by Spanish investors).
The train operations were part of the following 3 concessions starting from 1923: CFM (Chemins de Fer du Maroc), held by French Paris-Orléans (Sidi Kacem-Marrakech), TF (Tangier-Fez), held by French PLM and Spain, and CMO (Chemin de Fer du Maroc Oriental), part of the mining concession of Bouarfa (Fez-Oujda-Bouarfa).
CFM and CMO remained few years even after the independence in 1956. These were later merged into the current ONCF in 1963.