UNPKG

12.3 kBJavaScriptView Raw
1const { join, relative, resolve, sep, dirname } = require("path");
2
3const webpack = require("webpack");
4const nsWebpack = require("nativescript-dev-webpack");
5const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target");
6const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap");
7const { nsReplaceLazyLoader } = require("nativescript-dev-webpack/transformers/ns-replace-lazy-loader");
8const { nsSupportHmrNg } = require("nativescript-dev-webpack/transformers/ns-support-hmr-ng");
9const { getMainModulePath } = require("nativescript-dev-webpack/utils/ast-utils");
10const CleanWebpackPlugin = require("clean-webpack-plugin");
11const CopyWebpackPlugin = require("copy-webpack-plugin");
12const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
13const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin");
14const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
15const { AngularCompilerPlugin } = require("@ngtools/webpack");
16
17module.exports = env => {
18 // Add your custom Activities, Services and other Android app components here.
19 const appComponents = [
20 "tns-core-modules/ui/frame",
21 "tns-core-modules/ui/frame/activity",
22 ];
23
24 const platform = env && (env.android && "android" || env.ios && "ios");
25 if (!platform) {
26 throw new Error("You need to provide a target platform!");
27 }
28
29 const projectRoot = __dirname;
30
31 // Default destination inside platforms/<platform>/...
32 const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot));
33 const appResourcesPlatformDir = platform === "android" ? "Android" : "iOS";
34
35 const {
36 // The 'appPath' and 'appResourcesPath' values are fetched from
37 // the nsconfig.json configuration file
38 // when bundling with `tns run android|ios --bundle`.
39 appPath = "src",
40 appResourcesPath = "App_Resources",
41
42 // You can provide the following flags when running 'tns run android|ios'
43 aot, // --env.aot
44 snapshot, // --env.snapshot
45 uglify, // --env.uglify
46 report, // --env.report
47 sourceMap, // --env.sourceMap
48 hmr, // --env.hmr,
49 } = env;
50
51 const externals = nsWebpack.getConvertedExternals(env.externals);
52 const appFullPath = resolve(projectRoot, appPath);
53 const appResourcesFullPath = resolve(projectRoot, appResourcesPath);
54 const tsConfigName = "tsconfig.tns.json";
55 const entryModule = `${nsWebpack.getEntryModule(appFullPath)}.ts`;
56 const entryPath = `.${sep}${entryModule}`;
57 const ngCompilerTransformers = [];
58 const additionalLazyModuleResources = [];
59 if (aot) {
60 ngCompilerTransformers.push(nsReplaceBootstrap);
61 }
62
63 if (hmr) {
64 ngCompilerTransformers.push(nsSupportHmrNg);
65 }
66
67 // when "@angular/core" is external, it's not included in the bundles. In this way, it will be used
68 // directly from node_modules and the Angular modules loader won't be able to resolve the lazy routes
69 // fixes https://github.com/NativeScript/nativescript-cli/issues/4024
70 if (env.externals && env.externals.indexOf("@angular/core") > -1) {
71 const appModuleRelativePath = getMainModulePath(resolve(appFullPath, entryModule), tsConfigName);
72 if (appModuleRelativePath) {
73 const appModuleFolderPath = dirname(resolve(appFullPath, appModuleRelativePath));
74 // include the lazy loader inside app module
75 ngCompilerTransformers.push(nsReplaceLazyLoader);
76 // include the new lazy loader path in the allowed ones
77 additionalLazyModuleResources.push(appModuleFolderPath);
78 }
79 }
80
81 const ngCompilerPlugin = new AngularCompilerPlugin({
82 hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]),
83 platformTransformers: ngCompilerTransformers.map(t => t(() => ngCompilerPlugin, resolve(appFullPath, entryModule))),
84 mainPath: resolve(appPath, entryModule),
85 tsConfigPath: join(__dirname, tsConfigName),
86 skipCodeGeneration: !aot,
87 sourceMap: !!sourceMap,
88 additionalLazyModuleResources: additionalLazyModuleResources
89 });
90
91 const config = {
92 mode: uglify ? "production" : "development",
93 context: appFullPath,
94 externals,
95 watchOptions: {
96 ignored: [
97 appResourcesFullPath,
98 // Don't watch hidden files
99 "**/.*",
100 ]
101 },
102 target: nativescriptTarget,
103 entry: {
104 bundle: entryPath,
105 },
106 output: {
107 pathinfo: false,
108 path: dist,
109 libraryTarget: "commonjs2",
110 filename: "[name].js",
111 globalObject: "global",
112 },
113 resolve: {
114 extensions: [".ts", ".js", ".scss", ".css"],
115 // Resolve {N} system modules from tns-core-modules
116 modules: [
117 resolve(__dirname, "node_modules/tns-core-modules"),
118 resolve(__dirname, "node_modules"),
119 "node_modules/tns-core-modules",
120 "node_modules",
121 ],
122 alias: {
123 '~': appFullPath
124 },
125 symlinks: true
126 },
127 resolveLoader: {
128 symlinks: false
129 },
130 node: {
131 // Disable node shims that conflict with NativeScript
132 "http": false,
133 "timers": false,
134 "setImmediate": false,
135 "fs": "empty",
136 "__dirname": false,
137 },
138 devtool: sourceMap ? "inline-source-map" : "none",
139 optimization: {
140 splitChunks: {
141 cacheGroups: {
142 vendor: {
143 name: "vendor",
144 chunks: "all",
145 test: (module, chunks) => {
146 const moduleName = module.nameForCondition ? module.nameForCondition() : '';
147 return /[\\/]node_modules[\\/]/.test(moduleName) ||
148 appComponents.some(comp => comp === moduleName);
149 },
150 enforce: true,
151 },
152 }
153 },
154 minimize: !!uglify,
155 minimizer: [
156 new UglifyJsPlugin({
157 parallel: true,
158 cache: true,
159 uglifyOptions: {
160 output: {
161 comments: false,
162 },
163 compress: {
164 // The Android SBG has problems parsing the output
165 // when these options are enabled
166 'collapse_vars': platform !== "android",
167 sequences: platform !== "android",
168 }
169 }
170 })
171 ],
172 },
173 module: {
174 rules: [
175 {
176 test: new RegExp(entryPath),
177 use: [
178 // Require all Android app components
179 platform === "android" && {
180 loader: "nativescript-dev-webpack/android-app-components-loader",
181 options: { modules: appComponents }
182 },
183
184 {
185 loader: "nativescript-dev-webpack/bundle-config-loader",
186 options: {
187 angular: true,
188 loadCss: !snapshot, // load the application css if in debug mode
189 }
190 },
191 ].filter(loader => !!loader)
192 },
193
194 { test: /\.html$|\.xml$/, use: "raw-loader" },
195
196 // tns-core-modules reads the app.css and its imports using css-loader
197 {
198 test: /[\/|\\]app\.css$/,
199 use: [
200 "nativescript-dev-webpack/style-hot-loader",
201 { loader: "css-loader", options: { minimize: false, url: false } }
202 ]
203 },
204 {
205 test: /[\/|\\]app\.scss$/,
206 use: [
207 "nativescript-dev-webpack/style-hot-loader",
208 { loader: "css-loader", options: { minimize: false, url: false } },
209 "sass-loader"
210 ]
211 },
212
213 // Angular components reference css files and their imports using raw-loader
214 { test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: "raw-loader" },
215 { test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: ["raw-loader", "resolve-url-loader", "sass-loader"] },
216
217 {
218 test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
219 use: [
220 "nativescript-dev-webpack/moduleid-compat-loader",
221 "nativescript-dev-webpack/lazy-ngmodule-hot-loader",
222 "@ngtools/webpack",
223 ]
224 },
225
226 // Mark files inside `@angular/core` as using SystemJS style dynamic imports.
227 // Removing this will cause deprecation warnings to appear.
228 {
229 test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
230 parser: { system: true },
231 },
232 ],
233 },
234 plugins: [
235 // Define useful constants like TNS_WEBPACK
236 new webpack.DefinePlugin({
237 "global.TNS_WEBPACK": "true",
238 "process": undefined,
239 }),
240 // Remove all files from the out dir.
241 new CleanWebpackPlugin([`${dist}/**/*`]),
242 // Copy native app resources to out dir.
243 new CopyWebpackPlugin([
244 {
245 from: `${appResourcesFullPath}/${appResourcesPlatformDir}`,
246 to: `${dist}/App_Resources/${appResourcesPlatformDir}`,
247 context: projectRoot
248 },
249 ]),
250 // Copy assets to out dir. Add your own globs as needed.
251 new CopyWebpackPlugin([
252 { from: { glob: "fonts/**" } },
253 { from: { glob: "**/*.jpg" } },
254 { from: { glob: "**/*.png" } },
255 ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),
256 // Generate a bundle starter script and activate it in package.json
257 new nsWebpack.GenerateBundleStarterPlugin([
258 "./vendor",
259 "./bundle",
260 ]),
261 // For instructions on how to set up workers with webpack
262 // check out https://github.com/nativescript/worker-loader
263 new NativeScriptWorkerPlugin(),
264 ngCompilerPlugin,
265 // Does IPC communication with the {N} CLI to notify events when running in watch mode.
266 new nsWebpack.WatchStateLoggerPlugin(),
267 ],
268 };
269
270
271 if (report) {
272 // Generate report files for bundles content
273 config.plugins.push(new BundleAnalyzerPlugin({
274 analyzerMode: "static",
275 openAnalyzer: false,
276 generateStatsFile: true,
277 reportFilename: resolve(projectRoot, "report", `report.html`),
278 statsFilename: resolve(projectRoot, "report", `stats.json`),
279 }));
280 }
281
282 if (snapshot) {
283 config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({
284 chunk: "vendor",
285 angular: true,
286 requireModules: [
287 "reflect-metadata",
288 "@angular/platform-browser",
289 "@angular/core",
290 "@angular/common",
291 "@angular/router",
292 "nativescript-angular/platform-static",
293 "nativescript-angular/router",
294 ],
295 projectRoot,
296 webpackConfig: config,
297 }));
298 }
299
300 if (hmr) {
301 config.plugins.push(new webpack.HotModuleReplacementPlugin());
302 }
303
304 return config;
305};