Angular Workspace 带有两个 Angular + Nativescript 代码共享项目 + 库 [英] Angular Workspace with two Angular + Nativescript Code sharing Project + Library
问题描述
我有这样的结构:
AngularWorkspace/|--应用程序/||——|--dist/||--|--node_modules/||--|--项目/||--图书馆/||--AngularNativescriptAppOne/|||--App_Resources|||--src||||--应用程序/||||--资产/||||--环境/||||--环境/语言环境||||--environments/package.json||||--environments/tsconfig.app.json||||--环境/main.ts||||--environments/main.ns.ts||--AngularNativescriptAppTwo/|||--App_Resources/|||--src/||||--应用程序/||||--资产/||||--环境/||||--环境/语言环境||||--environments/package.json||||--environments/tsconfig.app.json||||--环境/main.ts||||--environments/main.ns.ts|--angular.json|--nsconfig.json|--package.json|--package.lock.json|--tsconfig.json|--tsconfig.tns.json|--tslint.json|--webpack.config.json
我想要在两个应用程序之间使用一个公共库.使用 ng build
和 ng serve
运行网站一切正常.
然而,问题在于尝试为每个应用程序运行 Nativescript 构建.我可能会让它们使用 package.json
和节点模块以及添加到每个应用程序的文件,但这变得难以管理,这就是为什么我为多个项目使用 Angular 工作空间结构.>
我能看到这个工作的唯一方法是更新 webpack.config.js 文件以及 passign 参数以用于路径,例如我目前尝试使用的路径:
tns 运行 android --bundle --env.path=/projects/AngularNativescriptAppOne/src --env.appResourcesPath=projects/AngularNativescriptAppOne/App_Resources
默认的webpack文件是这样的:
const { join, relative, resolve, sep } = require("path");const webpack = require("webpack");const nsWebpack = require("nativescript-dev-webpack");const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");const CleanWebpackPlugin = require("clean-webpack-plugin");const CopyWebpackPlugin = require("copy-webpack-plugin");const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");const UglifyJsPlugin = require("uglifyjs-webpack-plugin");const { AngularCompilerPlugin } = require("@ngtools/webpack");module.exports = env =>{//在此处添加您的自定义活动、服务和其他 Android 应用程序组件.const appComponents = ["tns-core-modules/ui/frame","tns-core-modules/ui/frame/activity",];const 平台 = 环境 &&(env.android && "android" || env.ios && "ios");如果(!平台){throw new Error("你需要提供一个目标平台!");}const projectRoot = __dirname;//平台内的默认目标/<平台>/...const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));const appResourcesPlatformDir = platform === "android" ?"安卓": "iOS";常量{//'appPath' 和 'appResourcesPath' 值是从//nsconfig.json 配置文件//与 `tns 捆绑时,运行 android|ios --bundle`.appPath = "app",appResourcesPath = "app/App_Resources",//你可以在运行 'tns run android|ios' 时提供以下标志aot,//--env.aot快照,//--env.snapshot丑化,//--env.uglify报告,//--env.reportsourceMap,//--env.sourceMaphmr,//--env.hmr,} = 环境;const externals = (env.externals || []).map((e) => {//--env.externalsreturn new RegExp(e + ".*");});const appFullPath = resolve(projectRoot, appPath);const appResourcesFullPath = resolve(projectRoot, appResourcesPath);const entryModule = `${nsWebpack.getEntryModule(appFullPath)}.ts`;const entryPath = `.${sep}${entryModule}`;const ngCompilerPlugin = 新的 AngularCompilerPlugin({hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),平台变形金刚:aot ?[nsReplaceBootstrap(() => ngCompilerPlugin)] : null,mainPath: 解析(appPath, entryModule),tsConfigPath: join(__dirname, "tsconfig.tns.json"),跳过代码生成:!aot,源映射:!!源映射,});常量配置 = {模式:丑化?"生产" : "开发",上下文:appFullPath,外部,手表选项:{忽略:[应用程序资源全路径,//不看隐藏文件"**/.*",]},目标:nativescriptTarget,入口: {包:入口路径,},输出: {路径信息:假,路径:dist,libraryTarget: "commonjs2",文件名:[名称].js",globalObject: "全局",},解决: {扩展名:[".ts", ".js", ".scss", ".css"],//从 tns-core-modules 解析 {N} 个系统模块模块: [解析(__dirname,node_modules/tns-core-modules"),解析(__dirname,node_modules"),"node_modules/tns-core-modules",节点模块",],别名:{'~': appFullPath},符号链接:真的},解析加载器:{符号链接:假},节点:{//禁用与 NativeScript 冲突的节点垫片http":假,计时器":假,设置立即":假,"fs": "空",__dirname":假,},开发工具:源映射?"inline-source-map" : "none",优化: {splitChunks:{缓存组:{小贩: {名称:供应商",块:全部",测试:(模块,块)=>{const moduleName = module.nameForCondition ?module.nameForCondition() : '';返回/[\\/]node_modules[\\/]/.test(moduleName) ||appComponents.some(comp => comp === moduleName);},强制执行:真实,},}},最小化:!!丑化,最小化:[新的 UglifyJsPlugin({平行:真实,缓存:真实,丑化选项:{输出: {评论:假的,},压缩:{//Android SBG 在解析输出时出现问题//当这些选项被启用时'collapse_vars': 平台 !== "android",序列:平台!==android",}}})],},模块: {规则: [{测试:新的正则表达式(entryPath),用: [//需要所有 Android 应用组件平台 === "android" &&{loader: "nativescript-dev-webpack/android-app-components-loader",选项:{ 模块:appComponents }},{loader: "nativescript-dev-webpack/bundle-config-loader",选项: {角度:真实,loadCss: !snapshot,//在调试模式下加载应用程序 css}},].filter(loader => !!loader)},{ 测试:/\.html$|\.xml$/, 使用: "raw-loader" },//tns-core-modules 使用 css-loader 读取 app.css 及其导入{测试:/[\/|\\]app\.css$/,用: {加载器:css-加载器",选项:{最小化:假,网址:假},}},{测试:/[\/|\\]app\.scss$/,用: [{ loader: "css-loader", 选项: { 最小化: false, url: false } },sass加载器"]},//Angular 组件使用 raw-loader 引用 css 文件及其导入{ 测试:/\.css$/, 排除:/[\/|\\]app\.css$/, 使用: "raw-loader" },{ 测试:/\.scss$/,排除:/[\/|\\]app\.scss$/,使用:["raw-loader", "resolve-url-loader", "sass-loader"]},{测试:/(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,用: ["nativescript-dev-webpack/moduleid-compat-loader","@ngtools/webpack",]},//将 `@angular/core` 中的文件标记为使用 SystemJS 风格的动态导入.//删除它会导致出现弃用警告.{测试:/[\/\\]@angular[\/\\]core[\/\\].+\.js$/,解析器:{系统:真},},],},插件: [//定义有用的常量,如 TNS_WEBPACK新的 webpack.DefinePlugin({"global.TNS_WEBPACK": "true",过程":未定义,}),//从 out 目录中删除所有文件.new CleanWebpackPlugin([`${dist}/**/*`]),//将本机应用程序资源复制到 out 目录.新的 CopyWebpackPlugin([{来自:`${appResourcesFullPath}/${appResourcesPlatformDir}`,到:`${dist}/App_Resources/${appResourcesPlatformDir}`,上下文:projectRoot},]),//将资产复制到 out 目录.根据需要添加您自己的 glob.新的 CopyWebpackPlugin([{ from: { glob: "fonts/**" } },{ from: { glob: "**/*.jpg" } },{ from: { glob: "**/*.png" } },], { 忽略: [`${relative(appPath, appResourcesFullPath)}/**`] }),//生成一个 bundle starter 脚本并在 package.json 中激活它新的 nsWebpack.GenerateBundleStarterPlugin([./小贩",./捆",]),//有关如何使用 webpack 设置 worker 的说明//查看 https://github.com/nativescript/worker-loader新的 NativeScriptWorkerPlugin(),ng编译器插件,//在监视模式下运行时,是否与 {N} CLI 进行 IPC 通信以通知事件.新的 nsWebpack.WatchStateLoggerPlugin(),],};如果(报告){//生成包内容的报告文件config.plugins.push(new BundleAnalyzerPlugin({分析器模式:静态",openAnalyzer:假,generateStatsFile: 真,报告文件名:解析(projectRoot,报告",`report.html`),statsFilename: resolve(projectRoot, "report", `stats.json`),}));}如果(快照){config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({块:供应商",角度:真实,要求模块:[反映元数据","@angular/platform-browser","@angular/核心","@angular/common","@angular/路由器",本地脚本角度/平台静态","nativescript-angular/router",],项目根,webpackConfig:配置,}));}如果(先生){config.plugins.push(new webpack.HotModuleReplacementPlugin());}返回配置;};
我的更新尝试使用我传递的值是这样的:
const { join, relative, resolve, sep } = require("path");const webpack = require("webpack");const nsWebpack = require("nativescript-dev-webpack");const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");const CleanWebpackPlugin = require("clean-webpack-plugin");const CopyWebpackPlugin = require("copy-webpack-plugin");const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");const UglifyJsPlugin = require("uglifyjs-webpack-plugin");const { AngularCompilerPlugin } = require("@ngtools/webpack");module.exports = env =>{//在此处添加您的自定义活动、服务和其他 Android 应用程序组件.const appComponents = ["tns-core-modules/ui/frame","tns-core-modules/ui/frame/activity",];const 平台 = 环境 &&(env.android && "android" || env.ios && "ios");如果(!平台){throw new Error("你需要提供一个目标平台!");}const projectRoot = __dirname;//平台内的默认目标/<平台>/...const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));const appResourcesPlatformDir = platform === "android" ?"安卓": "iOS";常量{//'appPath' 和 'appResourcesPath' 值是从//nsconfig.json 配置文件//与 `tns 捆绑时,运行 android|ios --bundle`.appPath = "app",appResourcesPath = "app/App_Resources",//你可以在运行 'tns run android|ios' 时提供以下标志aot,//--env.aot快照,//--env.snapshot丑化,//--env.uglify报告,//--env.reportsourceMap,//--env.sourceMaphmr,//--env.hmr,} = 环境;const externals = (env.externals || []).map((e) => {//--env.externalsreturn new RegExp(e + ".*");});const appFullPath = resolve(projectRoot, appPath);const appResourcesFullPath = resolve(projectRoot, appResourcesPath);const entryModule = `${nsWebpack.getEntryModule(appFullPath)}.ts`;const entryPath = `.${sep}${entryModule}`;const ngCompilerPlugin = 新的 AngularCompilerPlugin({hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),平台变形金刚:aot ?[nsReplaceBootstrap(() => ngCompilerPlugin)] : null,mainPath: 解析(appPath, entryModule),tsConfigPath: join(__dirname, "tsconfig.tns.json"),跳过代码生成:!aot,源映射:!!源映射,});常量配置 = {模式:丑化?"生产" : "开发",上下文:appFullPath,外部,手表选项:{忽略:[应用程序资源全路径,//不看隐藏文件"**/.*",]},目标:nativescriptTarget,入口: {包:入口路径,},输出: {路径信息:假,路径:dist,libraryTarget: "commonjs2",文件名:[名称].js",globalObject: "全局",},解决: {扩展名:[".ts", ".js", ".scss", ".css"],//从 tns-core-modules 解析 {N} 个系统模块模块: [解析(__dirname,node_modules/tns-core-modules"),解析(__dirname,node_modules"),"node_modules/tns-core-modules",节点模块",],别名:{'~': appFullPath},符号链接:真的},解析加载器:{符号链接:假},节点:{//禁用与 NativeScript 冲突的节点垫片http":假,计时器":假,设置立即":假,"fs": "空",__dirname":假,},开发工具:源映射?"inline-source-map" : "none",优化: {splitChunks:{缓存组:{小贩: {名称:供应商",块:全部",测试:(模块,块)=>{const moduleName = module.nameForCondition ?module.nameForCondition() : '';返回/[\\/]node_modules[\\/]/.test(moduleName) ||appComponents.some(comp => comp === moduleName);},强制执行:真实,},}},最小化:!!丑化,最小化:[新的 UglifyJsPlugin({平行:真实,缓存:真实,丑化选项:{输出: {评论:假的,},压缩:{//Android SBG 在解析输出时出现问题//当这些选项被启用时'collapse_vars': 平台 !== "android",序列:平台!==android",}}})],},模块: {规则: [{测试:新的正则表达式(entryPath),用: [//需要所有 Android 应用组件平台 === "android" &&{loader: "nativescript-dev-webpack/android-app-components-loader",选项:{ 模块:appComponents }},{loader: "nativescript-dev-webpack/bundle-config-loader",选项: {角度:真实,loadCss: !snapshot,//在调试模式下加载应用程序 css}},].filter(loader => !!loader)},{ 测试:/\.html$|\.xml$/, 使用: "raw-loader" },//tns-core-modules 使用 css-loader 读取 app.css 及其导入{测试:/[\/|\\]app\.css$/,用: {加载器:css-加载器",选项:{最小化:假,网址:假},}},{测试:/[\/|\\]app\.scss$/,用: [{ loader: "css-loader", 选项: { 最小化: false, url: false } },sass加载器"]},//Angular 组件使用 raw-loader 引用 css 文件及其导入{ 测试:/\.css$/, 排除:/[\/|\\]app\.css$/, 使用: "raw-loader" },{ 测试:/\.scss$/,排除:/[\/|\\]app\.scss$/,使用:["raw-loader", "resolve-url-loader", "sass-loader"]},{测试:/(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,用: ["nativescript-dev-webpack/moduleid-compat-loader","@ngtools/webpack",]},//将 `@angular/core` 中的文件标记为使用 SystemJS 风格的动态导入.//删除它会导致出现弃用警告.{测试:/[\/\\]@angular[\/\\]core[\/\\].+\.js$/,解析器:{系统:真},},],},插件: [//定义有用的常量,如 TNS_WEBPACK新的 webpack.DefinePlugin({"global.TNS_WEBPACK": "true",过程":未定义,}),//从 out 目录中删除所有文件.new CleanWebpackPlugin([`${dist}/**/*`]),//将本机应用程序资源复制到 out 目录.新的 CopyWebpackPlugin([{来自:`${appResourcesFullPath}/${appResourcesPlatformDir}`,到:`${dist}/App_Resources/${appResourcesPlatformDir}`,上下文:projectRoot},]),//将资产复制到 out 目录.根据需要添加您自己的 glob.新的 CopyWebpackPlugin([{ from: { glob: "fonts/**" } },{ from: { glob: "**/*.jpg" } },{ from: { glob: "**/*.png" } },], { 忽略: [`${relative(appPath, appResourcesFullPath)}/**`] }),//生成一个 bundle starter 脚本并在 package.json 中激活它新的 nsWebpack.GenerateBundleStarterPlugin([./小贩",./捆",]),//有关如何使用 webpack 设置 worker 的说明//查看 https://github.com/nativescript/worker-loader新的 NativeScriptWorkerPlugin(),ng编译器插件,//在监视模式下运行时,是否与 {N} CLI 进行 IPC 通信以通知事件.新的 nsWebpack.WatchStateLoggerPlugin(),],};如果(报告){//生成包内容的报告文件config.plugins.push(new BundleAnalyzerPlugin({分析器模式:静态",openAnalyzer:假,generateStatsFile: 真,报告文件名:解析(projectRoot,报告",`report.html`),statsFilename: resolve(projectRoot, "report", `stats.json`),}));}如果(快照){config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({块:供应商",角度:真实,要求模块:[反映元数据","@angular/platform-browser","@angular/核心","@angular/common","@angular/路由器",本地脚本角度/平台静态","nativescript-angular/router",],项目根,webpackConfig:配置,}));}如果(先生){config.plugins.push(new webpack.HotModuleReplacementPlugin());}返回配置;};
我确信我可以通过 webpack.json 以某种方式做到这一点,但我还没有成功.
我编辑的 webpack.json 文件会在构建中走得很远,但似乎找不到 package.json.以下错误是:
(node:865812) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'C:\Users\userameHere\Documents\MyProjects\AngularWorkspace\src\package.json'
很抱歉,这只是一个超链接答案,但在我看来,回答这个问题所需的空间太大了.我刚刚完成了一个repo我一直在工作来做到这一点.我有一大堆 angular web 库,现在我想使用 NativeScript 将它们用于移动设备.我已经把我到目前为止学到的一切都放到了这个 repo 中,希望对你有所帮助
I have a structure like this:
AngularWorkspace/
|--app/
| | --
|--dist/
| |--
|--node_modules/
| |--
|--projects/
| |--library/
| |--AngularNativescriptAppOne/
| | |--App_Resources
| | |--src
| | | |--app/
| | | |--assets/
| | | |--environments/
| | | |--environments/locale
| | | |--environments/package.json
| | | |--environments/tsconfig.app.json
| | | |--environments/main.ts
| | | |--environments/main.ns.ts
| |--AngularNativescriptAppTwo/
| | |--App_Resources/
| | |--src/
| | | |--app/
| | | |--assets/
| | | |--environments/
| | | |--environments/locale
| | | |--environments/package.json
| | | |--environments/tsconfig.app.json
| | | |--environments/main.ts
| | | |--environments/main.ns.ts
|--angular.json
|--nsconfig.json
|--package.json
|--package.lock.json
|--tsconfig.json
|--tsconfig.tns.json
|--tslint.json
|--webpack.config.json
I would like to have a common Library to be used between both applications.
Everything is working fine for running the website with ng build
and ng serve
.
The problem however is trying to run the Nativescript builds for each application. I could probably get them to work with package.json
and node modules and the files added to each application however that becomes difficult to manage which is why I have the Angular work space structure for multiple projects.
The only way I can see this working is updating the webpack.config.js file as well as passign it parameters to use for the paths such as this one I am currently trying to use:
tns run android --bundle --env.path=/projects/AngularNativescriptAppOne/src --env.appResourcesPath=projects/AngularNativescriptAppOne/App_Resources
The webpack File by default is like this:
const { join, relative, resolve, sep } = require("path");
const webpack = require("webpack");
const nsWebpack = require("nativescript-dev-webpack");
const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");
const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const { AngularCompilerPlugin } = require("@ngtools/webpack");
module.exports = env => {
// Add your custom Activities, Services and other Android app components here.
const appComponents = [
"tns-core-modules/ui/frame",
"tns-core-modules/ui/frame/activity",
];
const platform = env && (env.android && "android" || env.ios && "ios");
if (!platform) {
throw new Error("You need to provide a target platform!");
}
const projectRoot = __dirname;
// Default destination inside platforms/<platform>/...
const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
const appResourcesPlatformDir = platform === "android" ? "Android" : "iOS";
const {
// The 'appPath' and 'appResourcesPath' values are fetched from
// the nsconfig.json configuration file
// when bundling with `tns run android|ios --bundle`.
appPath = "app",
appResourcesPath = "app/App_Resources",
// You can provide the following flags when running 'tns run android|ios'
aot, // --env.aot
snapshot, // --env.snapshot
uglify, // --env.uglify
report, // --env.report
sourceMap, // --env.sourceMap
hmr, // --env.hmr,
} = env;
const externals = (env.externals || []).map((e) => { // --env.externals
return new RegExp(e + ".*");
});
const appFullPath = resolve(projectRoot, appPath);
const appResourcesFullPath = resolve(projectRoot, appResourcesPath);
const entryModule = `${nsWebpack.getEntryModule(appFullPath)}.ts`;
const entryPath = `.${sep}${entryModule}`;
const ngCompilerPlugin = new AngularCompilerPlugin({
hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
platformTransformers: aot ? [nsReplaceBootstrap(() => ngCompilerPlugin)] : null,
mainPath: resolve(appPath, entryModule),
tsConfigPath: join(__dirname, "tsconfig.tns.json"),
skipCodeGeneration: !aot,
sourceMap: !!sourceMap,
});
const config = {
mode: uglify ? "production" : "development",
context: appFullPath,
externals,
watchOptions: {
ignored: [
appResourcesFullPath,
// Don't watch hidden files
"**/.*",
]
},
target: nativescriptTarget,
entry: {
bundle: entryPath,
},
output: {
pathinfo: false,
path: dist,
libraryTarget: "commonjs2",
filename: "[name].js",
globalObject: "global",
},
resolve: {
extensions: [".ts", ".js", ".scss", ".css"],
// Resolve {N} system modules from tns-core-modules
modules: [
resolve(__dirname, "node_modules/tns-core-modules"),
resolve(__dirname, "node_modules"),
"node_modules/tns-core-modules",
"node_modules",
],
alias: {
'~': appFullPath
},
symlinks: true
},
resolveLoader: {
symlinks: false
},
node: {
// Disable node shims that conflict with NativeScript
"http": false,
"timers": false,
"setImmediate": false,
"fs": "empty",
"__dirname": false,
},
devtool: sourceMap ? "inline-source-map" : "none",
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
name: "vendor",
chunks: "all",
test: (module, chunks) => {
const moduleName = module.nameForCondition ? module.nameForCondition() : '';
return /[\\/]node_modules[\\/]/.test(moduleName) ||
appComponents.some(comp => comp === moduleName);
},
enforce: true,
},
}
},
minimize: !!uglify,
minimizer: [
new UglifyJsPlugin({
parallel: true,
cache: true,
uglifyOptions: {
output: {
comments: false,
},
compress: {
// The Android SBG has problems parsing the output
// when these options are enabled
'collapse_vars': platform !== "android",
sequences: platform !== "android",
}
}
})
],
},
module: {
rules: [
{
test: new RegExp(entryPath),
use: [
// Require all Android app components
platform === "android" && {
loader: "nativescript-dev-webpack/android-app-components-loader",
options: { modules: appComponents }
},
{
loader: "nativescript-dev-webpack/bundle-config-loader",
options: {
angular: true,
loadCss: !snapshot, // load the application css if in debug mode
}
},
].filter(loader => !!loader)
},
{ test: /\.html$|\.xml$/, use: "raw-loader" },
// tns-core-modules reads the app.css and its imports using css-loader
{
test: /[\/|\\]app\.css$/,
use: {
loader: "css-loader",
options: { minimize: false, url: false },
}
},
{
test: /[\/|\\]app\.scss$/,
use: [
{ loader: "css-loader", options: { minimize: false, url: false } },
"sass-loader"
]
},
// Angular components reference css files and their imports using raw-loader
{ test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: "raw-loader" },
{ test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: ["raw-loader", "resolve-url-loader", "sass-loader"] },
{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
use: [
"nativescript-dev-webpack/moduleid-compat-loader",
"@ngtools/webpack",
]
},
// Mark files inside `@angular/core` as using SystemJS style dynamic imports.
// Removing this will cause deprecation warnings to appear.
{
test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
parser: { system: true },
},
],
},
plugins: [
// Define useful constants like TNS_WEBPACK
new webpack.DefinePlugin({
"global.TNS_WEBPACK": "true",
"process": undefined,
}),
// Remove all files from the out dir.
new CleanWebpackPlugin([`${dist}/**/*`]),
// Copy native app resources to out dir.
new CopyWebpackPlugin([
{
from: `${appResourcesFullPath}/${appResourcesPlatformDir}`,
to: `${dist}/App_Resources/${appResourcesPlatformDir}`,
context: projectRoot
},
]),
// Copy assets to out dir. Add your own globs as needed.
new CopyWebpackPlugin([
{ from: { glob: "fonts/**" } },
{ from: { glob: "**/*.jpg" } },
{ from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
// Generate a bundle starter script and activate it in package.json
new nsWebpack.GenerateBundleStarterPlugin([
"./vendor",
"./bundle",
]),
// For instructions on how to set up workers with webpack
// check out https://github.com/nativescript/worker-loader
new NativeScriptWorkerPlugin(),
ngCompilerPlugin,
// Does IPC communication with the {N} CLI to notify events when running in watch mode.
new nsWebpack.WatchStateLoggerPlugin(),
],
};
if (report) {
// Generate report files for bundles content
config.plugins.push(new BundleAnalyzerPlugin({
analyzerMode: "static",
openAnalyzer: false,
generateStatsFile: true,
reportFilename: resolve(projectRoot, "report", `report.html`),
statsFilename: resolve(projectRoot, "report", `stats.json`),
}));
}
if (snapshot) {
config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({
chunk: "vendor",
angular: true,
requireModules: [
"reflect-metadata",
"@angular/platform-browser",
"@angular/core",
"@angular/common",
"@angular/router",
"nativescript-angular/platform-static",
"nativescript-angular/router",
],
projectRoot,
webpackConfig: config,
}));
}
if (hmr) {
config.plugins.push(new webpack.HotModuleReplacementPlugin());
}
return config;
};
Mine updated trying to use my values passed is like this:
const { join, relative, resolve, sep } = require("path");
const webpack = require("webpack");
const nsWebpack = require("nativescript-dev-webpack");
const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");
const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const { AngularCompilerPlugin } = require("@ngtools/webpack");
module.exports = env => {
// Add your custom Activities, Services and other Android app components here.
const appComponents = [
"tns-core-modules/ui/frame",
"tns-core-modules/ui/frame/activity",
];
const platform = env && (env.android && "android" || env.ios && "ios");
if (!platform) {
throw new Error("You need to provide a target platform!");
}
const projectRoot = __dirname;
// Default destination inside platforms/<platform>/...
const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
const appResourcesPlatformDir = platform === "android" ? "Android" : "iOS";
const {
// The 'appPath' and 'appResourcesPath' values are fetched from
// the nsconfig.json configuration file
// when bundling with `tns run android|ios --bundle`.
appPath = "app",
appResourcesPath = "app/App_Resources",
// You can provide the following flags when running 'tns run android|ios'
aot, // --env.aot
snapshot, // --env.snapshot
uglify, // --env.uglify
report, // --env.report
sourceMap, // --env.sourceMap
hmr, // --env.hmr,
} = env;
const externals = (env.externals || []).map((e) => { // --env.externals
return new RegExp(e + ".*");
});
const appFullPath = resolve(projectRoot, appPath);
const appResourcesFullPath = resolve(projectRoot, appResourcesPath);
const entryModule = `${nsWebpack.getEntryModule(appFullPath)}.ts`;
const entryPath = `.${sep}${entryModule}`;
const ngCompilerPlugin = new AngularCompilerPlugin({
hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
platformTransformers: aot ? [nsReplaceBootstrap(() => ngCompilerPlugin)] : null,
mainPath: resolve(appPath, entryModule),
tsConfigPath: join(__dirname, "tsconfig.tns.json"),
skipCodeGeneration: !aot,
sourceMap: !!sourceMap,
});
const config = {
mode: uglify ? "production" : "development",
context: appFullPath,
externals,
watchOptions: {
ignored: [
appResourcesFullPath,
// Don't watch hidden files
"**/.*",
]
},
target: nativescriptTarget,
entry: {
bundle: entryPath,
},
output: {
pathinfo: false,
path: dist,
libraryTarget: "commonjs2",
filename: "[name].js",
globalObject: "global",
},
resolve: {
extensions: [".ts", ".js", ".scss", ".css"],
// Resolve {N} system modules from tns-core-modules
modules: [
resolve(__dirname, "node_modules/tns-core-modules"),
resolve(__dirname, "node_modules"),
"node_modules/tns-core-modules",
"node_modules",
],
alias: {
'~': appFullPath
},
symlinks: true
},
resolveLoader: {
symlinks: false
},
node: {
// Disable node shims that conflict with NativeScript
"http": false,
"timers": false,
"setImmediate": false,
"fs": "empty",
"__dirname": false,
},
devtool: sourceMap ? "inline-source-map" : "none",
optimization: {
splitChunks: {
cacheGroups: {
vendor: {
name: "vendor",
chunks: "all",
test: (module, chunks) => {
const moduleName = module.nameForCondition ? module.nameForCondition() : '';
return /[\\/]node_modules[\\/]/.test(moduleName) ||
appComponents.some(comp => comp === moduleName);
},
enforce: true,
},
}
},
minimize: !!uglify,
minimizer: [
new UglifyJsPlugin({
parallel: true,
cache: true,
uglifyOptions: {
output: {
comments: false,
},
compress: {
// The Android SBG has problems parsing the output
// when these options are enabled
'collapse_vars': platform !== "android",
sequences: platform !== "android",
}
}
})
],
},
module: {
rules: [
{
test: new RegExp(entryPath),
use: [
// Require all Android app components
platform === "android" && {
loader: "nativescript-dev-webpack/android-app-components-loader",
options: { modules: appComponents }
},
{
loader: "nativescript-dev-webpack/bundle-config-loader",
options: {
angular: true,
loadCss: !snapshot, // load the application css if in debug mode
}
},
].filter(loader => !!loader)
},
{ test: /\.html$|\.xml$/, use: "raw-loader" },
// tns-core-modules reads the app.css and its imports using css-loader
{
test: /[\/|\\]app\.css$/,
use: {
loader: "css-loader",
options: { minimize: false, url: false },
}
},
{
test: /[\/|\\]app\.scss$/,
use: [
{ loader: "css-loader", options: { minimize: false, url: false } },
"sass-loader"
]
},
// Angular components reference css files and their imports using raw-loader
{ test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: "raw-loader" },
{ test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: ["raw-loader", "resolve-url-loader", "sass-loader"] },
{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
use: [
"nativescript-dev-webpack/moduleid-compat-loader",
"@ngtools/webpack",
]
},
// Mark files inside `@angular/core` as using SystemJS style dynamic imports.
// Removing this will cause deprecation warnings to appear.
{
test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
parser: { system: true },
},
],
},
plugins: [
// Define useful constants like TNS_WEBPACK
new webpack.DefinePlugin({
"global.TNS_WEBPACK": "true",
"process": undefined,
}),
// Remove all files from the out dir.
new CleanWebpackPlugin([`${dist}/**/*`]),
// Copy native app resources to out dir.
new CopyWebpackPlugin([
{
from: `${appResourcesFullPath}/${appResourcesPlatformDir}`,
to: `${dist}/App_Resources/${appResourcesPlatformDir}`,
context: projectRoot
},
]),
// Copy assets to out dir. Add your own globs as needed.
new CopyWebpackPlugin([
{ from: { glob: "fonts/**" } },
{ from: { glob: "**/*.jpg" } },
{ from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
// Generate a bundle starter script and activate it in package.json
new nsWebpack.GenerateBundleStarterPlugin([
"./vendor",
"./bundle",
]),
// For instructions on how to set up workers with webpack
// check out https://github.com/nativescript/worker-loader
new NativeScriptWorkerPlugin(),
ngCompilerPlugin,
// Does IPC communication with the {N} CLI to notify events when running in watch mode.
new nsWebpack.WatchStateLoggerPlugin(),
],
};
if (report) {
// Generate report files for bundles content
config.plugins.push(new BundleAnalyzerPlugin({
analyzerMode: "static",
openAnalyzer: false,
generateStatsFile: true,
reportFilename: resolve(projectRoot, "report", `report.html`),
statsFilename: resolve(projectRoot, "report", `stats.json`),
}));
}
if (snapshot) {
config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({
chunk: "vendor",
angular: true,
requireModules: [
"reflect-metadata",
"@angular/platform-browser",
"@angular/core",
"@angular/common",
"@angular/router",
"nativescript-angular/platform-static",
"nativescript-angular/router",
],
projectRoot,
webpackConfig: config,
}));
}
if (hmr) {
config.plugins.push(new webpack.HotModuleReplacementPlugin());
}
return config;
};
I am sure I can somehow do this through the webpack.json but I have have not been successful yet.
Will my edited webpack.json file I get decently far in the build but it cannot seem to find the package.json. The following error is:
(node:865812) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'C:\Users\userameHere\Documents\MyProjects\AngularWorkspace\src\package.json'
I'm sorry this is just a hyperlink answer but the space required to answer this, in my opinion, is way too large. I just finished finalizing a repo I've been working on to do exactly this. I have a whole slew of angular web libraries that I now want to make available for use on mobile using NativeScript. I have put everything I have learned so far into this repo and I hope it helps you too.
这篇关于Angular Workspace 带有两个 Angular + Nativescript 代码共享项目 + 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!