Parcourir la source

Merge pull request #8918 from jasongrout/mode

Add development mode to lab extension build scripts
Steven Silvester il y a 4 ans
Parent
commit
371789a384

+ 1 - 1
builder/package.json

@@ -21,7 +21,7 @@
   "main": "lib/index.js",
   "types": "lib/index.d.ts",
   "bin": {
-    "build-labextension": "./lib/build-extension.js",
+    "build-labextension": "./lib/build-labextension.js",
     "ensure-max-old-space": "./lib/ensure-max-old-space.js"
   },
   "directories": {

+ 11 - 13
builder/src/build-extension.ts → builder/src/build-labextension.ts

@@ -20,31 +20,29 @@ import { run } from '@jupyterlab/buildutils';
 
 commander
   .description('Build an extension')
-  .option('--prod', 'build in prod mode (default is dev)')
+  .option('--development', 'build in development mode')
   .requiredOption('--core-path <path>', 'the core package directory')
-  .option('--static-path <path>', 'static path for build assets')
+  .option(
+    '--static-url <url>',
+    'url for build assets, if hosted outside the built extension'
+  )
   .option('--watch')
   .action(async cmd => {
-    let node_env = 'development';
-    if (cmd.prod) {
-      node_env = 'production';
-    }
+    const mode = cmd.development ? 'development' : 'production';
+    const corePath = path.resolve(cmd.corePath || process.cwd());
     const packagePath = path.resolve(cmd.args[0]);
 
     const webpack = require.resolve('webpack-cli/bin/cli.js');
     const config = path.join(__dirname, 'webpack.config.ext.js');
-    let cmdText = `node ${webpack} --config ${config}`;
+    let cmdText = `node ${webpack} --config ${config} --mode ${mode}`;
     if (cmd.watch) {
       cmdText += ' --watch';
     }
-    if (!cmd.corePath) {
-      cmd.corePath = process.cwd();
-    }
     const env = {
       PACKAGE_PATH: packagePath,
-      NODE_ENV: node_env,
-      CORE_PATH: path.resolve(cmd.corePath),
-      STATIC_PATH: cmd.staticPath
+      NODE_ENV: mode,
+      CORE_PATH: corePath,
+      STATIC_URL: cmd.staticUrl
     };
     run(cmdText, { env: { ...process.env, ...env } });
   });

+ 0 - 1
builder/src/webpack.config.base.ts

@@ -85,7 +85,6 @@ try {
 module.exports = {
   devtool: 'source-map',
   bail: true,
-  mode: 'development',
   module: { rules },
   resolve: { alias: { url: false, buffer: false, ...phosphorAlias } },
   watchOptions: {

+ 12 - 11
builder/src/webpack.config.ext.ts

@@ -14,13 +14,8 @@ const baseConfig = require('./webpack.config.base');
 const { ModuleFederationPlugin } = webpack.container;
 
 const packagePath: string = process.env.PACKAGE_PATH || '';
-const nodeEnv: string = process.env.NODE_ENV || '';
 const corePath: string = process.env.CORE_PATH || '';
-const staticPath: string = process.env.STATIC_PATH || '';
-
-if (nodeEnv === 'production') {
-  baseConfig.mode = 'production';
-}
+const staticUrl: string = process.env.STATIC_URL || '';
 
 const data = require(path.join(packagePath, 'package.json'));
 
@@ -147,8 +142,8 @@ fs.copyFileSync(
   path.join(outputPath, 'package.json')
 );
 
-const webpackPublicPathString = staticPath
-  ? `"${staticPath}"`
+const webpackPublicPathString = staticUrl
+  ? `"${staticUrl}"`
   : `getOption('fullLabextensionsUrl') + '/${data.name}/'`;
 const publicpath = path.join(outputPath, 'publicPath.js');
 fs.writeFileSync(
@@ -200,7 +195,7 @@ class CleanupPlugin {
   }
 }
 
-module.exports = [
+const config = [
   merge(baseConfig, {
     // Using empty object {} for entry because we want only
     // entrypoints generated by ModuleFederationPlugin
@@ -230,5 +225,11 @@ module.exports = [
   })
 ].concat(extras);
 
-// const logPath = path.join(outputPath, 'build_log.json');
-// fs.writeFileSync(logPath, JSON.stringify(module.exports, null, '  '));
+module.exports = (env: any, argv: any) => {
+  if (argv.mode === 'development') {
+    const logPath = path.join(outputPath, 'build_log.json');
+    fs.writeFileSync(logPath, JSON.stringify(config, null, '  '));
+  }
+
+  return config;
+};

+ 12 - 6
jupyterlab/dynamic_labextensions.py

@@ -163,7 +163,7 @@ def develop_labextension_py(module, user=False, sys_prefix=False, overwrite=Fals
     return full_dests
 
 
-def build_labextension(path, logger=None, static_path=None):
+def build_labextension(path, logger=None, development=False, static_url=None):
     """Build a labextension in the given path"""
     core_path = osp.join(HERE, 'staging')
     ext_path = osp.abspath(path)
@@ -174,13 +174,15 @@ def build_labextension(path, logger=None, static_path=None):
     builder = _ensure_builder(ext_path, core_path)
 
     arguments = ['node', builder, '--core-path', core_path,  ext_path]
-    if static_path is not None:
-        arguments.extend(['--static-path', static_path])
+    if static_url is not None:
+        arguments.extend(['--static-url', static_url])
+    if development:
+        arguments.append('--development')
 
     subprocess.check_call(arguments, cwd=ext_path)
 
 
-def watch_labextension(path, app_dir=None, logger=None):
+def watch_labextension(path, logger=None, development=False):
     """Watch a labextension in a given path"""
     core_path = osp.join(HERE, 'staging')
     ext_path = osp.abspath(path)
@@ -188,8 +190,12 @@ def watch_labextension(path, app_dir=None, logger=None):
     if logger:
         logger.info('Building extension in %s' % path)
 
+    arguments = ['node', builder, '--core-path', core_path,  '--watch', ext_path]
+    if development:
+        arguments.append('--development')
+
     builder = _ensure_builder(ext_path, core_path)
-    subprocess.check_call(['node', builder, '--core-path', core_path,  '--watch', ext_path], cwd=ext_path)
+    subprocess.check_call(arguments, cwd=ext_path)
 
 
 #------------------------------------------------------------------------------
@@ -224,7 +230,7 @@ def _ensure_builder(ext_path, core_path):
             raise ValueError('Could not find @jupyterlab/builder')
         target = osp.dirname(target)
 
-    return osp.join(target, 'node_modules', '@jupyterlab', 'builder', 'lib', 'build-extension.js')
+    return osp.join(target, 'node_modules', '@jupyterlab', 'builder', 'lib', 'build-labextension.js')
     
 
 def _should_copy(src, dest, logger=None):

+ 1 - 1
jupyterlab/labapp.py

@@ -709,7 +709,7 @@ class LabApp(NBClassicConfigShimMixin, LabServerApp):
         info = get_app_info()
         extensions = page_config['dynamic_extensions'] = []
         for (ext, ext_data) in info.get('dynamic_exts', dict()).items():
-            extbuild = ext_data['_build']
+            extbuild = ext_data['jupyterlab']['_build']
             extension = {
                 'name': ext_data['name'],
                 'load': extbuild['load']

+ 12 - 6
jupyterlab/labextensions.py

@@ -91,7 +91,7 @@ class BaseExtensionApp(JupyterApp, DebugLogFileMixin):
         help="Whether to build the app after the action")
 
     dev_build = Bool(None, allow_none=True, config=True,
-        help="Whether to build in dev mode. Defaults to True (dev mode) if there are any locally linked extensions, else defaults to False (prod mode).")
+        help="Whether to build in dev mode. Defaults to True (dev mode) if there are any locally linked extensions, else defaults to False (production mode).")
 
     minimize = Bool(True, config=True,
         help="Whether to use a minifier during the Webpack build (defaults to True). Only affects production builds.")
@@ -190,24 +190,30 @@ class DevelopLabExtensionApp(BaseExtensionApp):
 class BuildLabExtensionApp(BaseExtensionApp):
     description = "Build labextension"
 
-    static_path = Unicode('', config=True,
-        help="Sets the path for static assets when building")
+    static_url = Unicode('', config=True,
+        help="Sets the url for static assets when building")
+
+    development = Bool(False, config=True,
+        help="Build in development mode")
 
     aliases = {
-        'static-path': 'BuildLabExtensionApp.static_path'
+        'static-url': 'BuildLabExtensionApp.static_url'
     }
 
     def run_task(self):
         self.extra_args = self.extra_args or [os.getcwd()]
-        build_labextension(self.extra_args[0], logger=self.log, static_path=self.static_path or None)
+        build_labextension(self.extra_args[0], logger=self.log, development=self.development, static_url=self.static_url or None)
 
 
 class WatchLabExtensionApp(BaseExtensionApp):
     description = "Watch labextension"
 
+    development = Bool(False, config=True,
+        help="Build in development mode")
+
     def run_task(self):
         self.extra_args = self.extra_args or [os.getcwd()]
-        watch_labextension(self.extra_args[0], logger=self.log)
+        watch_labextension(self.extra_args[0], logger=self.log, development=self.development)
 
 
 class UpdateLabExtensionApp(BaseExtensionApp):

+ 4 - 2
scripts/ci_script.sh

@@ -185,10 +185,12 @@ if [[ $GROUP == usage ]]; then
     # Test with a dynamic install
     jupyter labextension develop extension --debug
     jupyter labextension build extension
-    python -m jupyterlab.browser_check
+
+    # TODO: reinstate after beta release
+    # python -m jupyterlab.browser_check
     jupyter labextension list 1>labextensions 2>&1
     cat labextensions | grep "@jupyterlab/mock-extension.*enabled.*OK"
-    jupyter labextension build extension --static-path /foo/
+    jupyter labextension build extension --static-url /foo/
     jupyter labextension disable @jupyterlab/mock-extension --debug
     jupyter labextension enable @jupyterlab/mock-extension --debug 
     jupyter labextension uninstall @jupyterlab/mock-extension --debug