参考:https://blog.csdn.net/fengsh998/article/details/81388376
在本例中,介绍如何用webpack打包一个Nodejs前端项目, 这里的Nodejs代码用typescript编写
首先新建一个nodejs项目,添加所需的webpack模块
npm install --save webpack-dev-server npm install --save-dev webpack webpack-cli typescript ts-loader
执行tsc --init
新建src和dist文件夹,配置webpack.config.js
1 const path = require(‘path‘); 2 3 module.exports = { 4 entry: ‘./src/code.ts‘, 5 devtool: ‘inline-source-map‘, 6 module: { 7 rules: [ 8 { 9 test: /\.tsx?$/, 10 use: ‘ts-loader‘, 11 exclude: /node_modules/ 12 } 13 ] 14 }, 15 resolve: { 16 extensions: [‘.ts‘, ‘.js‘, ‘.jsx‘] 17 }, 18 output: { 19 filename: ‘bundle.js‘, 20 path: path.resolve(__dirname, ‘dist‘) 21 } 22 };
然后写我们的html,代码非常简单
1 <html> 2 <head> 3 <title>Rx Application</title> 4 <link rel="stylesheet" href="./style/main.css"> 5 <script src="https://unpkg.com/lodash@4.16.6"></script> 6 </head> 7 <body> 8 <ul id="output"> 9 10 </ul> 11 <script src="./dist/bundle.js"></script> 12 </body> 13 </html>
在src里新建code.ts,写代码,
本例中,实现一个简单的Reactivex Demo, 响应的函数会向DOM中添加列表元素
1 import {Observable} from "rxjs"; 2 console.log("Successfully load js code"); 3 var observable = Observable.create((observer:any) => { 4 try { 5 observer.next("Hello"); 6 observer.next("How are you"); 7 setInterval(() => { 8 observer.next("I am good"); 9 }, 2000); 10 } catch(err) { 11 observer.error(err); 12 } 13 }); 14 15 var observer = observable.subscribe( 16 (x:any) => addItem(x), 17 (error:any) => addItem(error), 18 () => addItem(‘Completed‘) 19 ); 20 21 setTimeout(() => { 22 observer.unsubscribe(); 23 }, 6000); 24 25 function addItem(val:any) { 26 var node = document.createElement("li"); 27 var textnode = document.createTextNode(val); 28 node.appendChild(textnode); 29 var nodeoutput = document.getElementById("output"); 30 if(nodeoutput){ 31 nodeoutput.appendChild(node); 32 } 33 }
在npm中添加命令:
"scripts": { "start": "webpack serve --mode development" },
( 如果是版本4之前的webpack,用这个命令: webpack-dev-server --mode development )
运行npm start,可见服务器启动
在浏览器中输入localhost:8080,可以看到已经成功部署