High-peak-power transform-limited narrow-linewidth nanosecond all-fiber lasers are desired in a range of applications. However, their linewidths will be broadened by self-phase modulation (SPM). We propose a novel concept that generates transform-limited laser pulses by temporally shaping the pulse seed. The impact of the pulse shape on SPM-induced spectral broadening was studied numerically and experimentally. It was found theoretically that the square-shape pulsed laser is immune to SPM-induced spectral broadening. Based on this principle, we built a high-peak-power, linearly polarized, square-shape nanosecond all-fiber laser in a master oscillator power amplifier (MOPA) configuration. Stimulated Brillouin scattering (SBS) limited peak powers of 4.02 kW, 5.06 kW, 6.52 kW and 9.30 kW were obtained at pulse widths of 8 ns, 7 ns, 6 ns and 5 ns. Thanks to the square-shape pulsed seed, the linewidths at maximum peak power remained at 129.5 MHz, 137.6 MHz, 156.2 MHz and 200.1 MHz, respectively, close to the transform-limited values of 110.8 MHz, 126.6 MHz, 147.7 MHz and 177.3 MHz.