How to run SPFx webpart using npm start
In this article we are going to learn how to execute SPFx Webpart locally without gulp for Flexible UI development. We can use webpack and run it like a traditional react way using "npm start" command. So you can access both "gulp serve" and "npm start" during development.
Before we going to start we need SPFx Environment Setup and Create New Webpart.
You can get the git repo HERE.
1. Install npm Packages
Install the below required npm packages in your SPFx solution.
This will install:
webpack-dev-server — this development server automatically rerun webpack when our file is changed
webpack-cli — enable running webpack from the command line
Note: Please make sure you have installed latest version of webpack. Else this is showing TypeError: Cannot read property 'tap' of undefined.
2. Add Script in Package.json
Add the following script to package.json
3. Create Index HTML
Now create an index.html file in your root project with the following content:
4. Update Index.tsx
Update this react code at "Src/index.tsx"
Note: If you facing any error in index.ts just change the extention "ts" to "tsx" and check it.
5. Add Webpack Config
Add below webpack.config.js in your SPFx project's root folder
6. Configuring Babel and Loaders
The React component we wrote above used the class syntax, which is a feature of ES6. Webpack needs Babel to process ES6 into ES5 syntaxes in order for this class to work. And need to configure appropriate loaders in webpack config. we already added all loader in setp 5. just install the below npm packages only.
Why we need these packages?
@babel/core is the main dependency that include babel transform script
@babel/preset-env is the default Babel preset used to transform ES6+ into valid ES5 code. Optionally configure browser polyfills automatically
@babel/preset-react is used for transforming JSX and React class syntax into valid JavaScript code
babel-loader is a webpack loader that hook Babel into webpack. We will run Babel from webpack with this package
html-webpack-plugin that simplifies creation of HTML files to serve your bundles
In order to use Babel presets, create a new .babelrc
file
All the setup is ready, now you can run following command to execute it.
Note: In SPFx using "module.scss". So please make sure you have installed updated version of npm loaders. otherwise style not loaded or shows error.
Hope This is working fine, Thanks for reading.