用html做的美食网站,海宁高端高端网站设计,巨鹿网站建设网络公司,网站的交互体验需求
后端有个nodejs 基础库#xff0c;用typescript编写#xff0c;需要发包到代码仓库上#xff0c;被其它业务引入。这其中就涉及了#xff1a; 编译#xff0c; 打包#xff0c;发包。
工作流速览 前提依赖
webpack主体
npm install --save-dev webpack webpack…需求
后端有个nodejs 基础库用typescript编写需要发包到代码仓库上被其它业务引入。这其中就涉及了 编译 打包发包。
工作流速览 前提依赖
webpack主体
npm install --save-dev webpack webpack-cliwebpack插件
npm install --save-dev webpack-node-externals ts-loader 编译相关
npm instsall --save-dev typescript基础示例 这个是工作流可以看到从最初的源文件一直到发包的打包文件的转换过程。这其中涉及到3个配置文件
package.json 用于包依赖管理(装依赖 和 发包)webpackage.config.js 用于触发编译(typescript编译) 和 打包(把编译后的文件 打到一个文件里tsconfig.json 用于编译使用将typescript文件编译成JavaScript文件。
tsconfig.json
{compilerOptions: {baseUrl: ./,declaration: true,allowSyntheticDefaultImports: true,skipLibCheck: true,emitDecoratorMetadata: true,resolveJsonModule: true,esModuleInterop: true,experimentalDecorators: true,lib: [es2015, es2016, es2017.object, es2020.Promise, esnext.asynciterable, dom],module: nodeNext,moduleResolution: nodeNext,noImplicitAny: false,outDir: ./dist,composite: true,sourceMap: true,strict: true,strictPropertyInitialization: false,target: es2017,types: [jest],// types: [node],typeRoots: [node_modules/types],},compileOnSave: true,include: [src/**/*, index.ts],exclude: [node_modules/**/*, **/*.d.ts, test],
}
webpack.config.js
const path require(path);
const nodeExternals require(webpack-node-externals);module.exports {entry: ./src/index.ts, // 指定入口文件为 src 目录下的 index.tstarget: node, // 指定打包目标为Node环境externals: [nodeExternals()], // 排除 node_modules 中的模块devtool: source-map,module: {rules: [{test: /\\.ts$/,use: ts-loader,exclude: /node_modules/,},],},resolve: {extensions: [.tsx, .ts, .js],preferRelative: true,},output: {filename: bundle.js, // 输出文件名path: path.resolve(__dirname, dist), // 输出目录设置为根目录下的 dist 文件夹libraryTarget: commonjs },
};
target: 指定运行时环境这里是在后端node环境运行填写node。exclude: 排除 node_module等不需要打包的文件。debug: source map, 关联打包文件和源文件以开启 vscode等IDE debug时的断点。编译会用tsconfig.json文件进行编译
编译后打包
npx webpack执行webpack的过程会先触发编译下然后打包 解释结果
编制结果在 dist文件夹里可以查看里面内容如下ls ./dist bundle.js 就是webpack打包的结果。 bundle.js.map 用于debug的文件source map参数开始后关联bundle.js和源码的文件。 index.d.ts 声明文件typescript 编译index.ts时产生的声明文件src 里包含了其它*.ts的声明文件。
发包
package.json
最后如果要发包注意下 package.json main的入口是打包的文件生成的地方
{name: nodejs-webpack-demo,version: 1.0.0,description: ,main: ./dist/bundle.js,types: ./dist/index.d.ts, scripts: {test: echo \\Error: no test specified\\ exit 1},author: ,license: ISC,devDependencies: {ts-loader: ^9.5.1,webpack: ^5.92.1,webpack-cli: ^5.1.4,webpack-node-externals: ^3.0.0},dependencies: {mongoose: ^8.4.4}
}
同时注意下webpack.config.js里面的output中的libraryTarget需要根据不同的运行环境输出为指定格式否则无法引入使用。
发包命令用npm发包进入到包的目录下
// 如果需要使用私有仓库
npm config set registry https://your-registry.com
// 登录
npm login
// 发包
npm publish
或是用 yarn 注意这个需要在 包的外层执行 假设你的包文件是common则需要在路径…/common 即包文件的外层执行
yarn publish --registryhttp://127.0.0.1:8081/repository/my-npm-repo/ --new-version 1.0.0 common代码参考
代码地址 https://github.com/Wunan777/webpack-demo