andrewwakeling / espruino-webpack-babel-sample

A sample project which uses Webpack & Babel for Espruino
16 stars 6 forks source link

import/require natively available packages #1

Open martinjuhasz opened 6 years ago

martinjuhasz commented 6 years ago
import WiFi from 'Wifi'
// or // const WiFi = require('Wifi')
WiFi.on('connected', () => { console.log('We have an IP Address') })

I tried using this webpack configuration with the native available packages from espruino like Wifi or MQTT but webpack failed resolving the paths.

ERROR in ./src/entry.js
Module not found: Error: Can't resolve 'Wifi' in '/Users/martinjuhasz/Downloads/espruino-webpack-babel-sample-master/src'

Any idea how to resolve this?

wilberforce commented 6 years ago

Not sure how to handle Native modules like wifi. For modules like MQTT you should be able to copy the module source into the src folder.

andrewwakeling commented 6 years ago

Apologies for not replying earlier. The following should get webpack to ignore usage of requiring a module:

const Wifi = global.require('Wifi');

I think there might be other ways, but this is a pretty easy approach.

wilberforce commented 6 years ago

webpack noob here.

Where would that line go?

Wouldn't this end up as part of the build?

wilberforce commented 6 years ago

I have made some progress with this. I'll clean it up and post - perhaps on the forum. I have setup a modules folder - and put the espruino modules in there... and then told webpack they are externals..

part is still hard coded...

const path = require('path');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

const fs = require('fs');

var directory='./src/modules';
var modules=fs.readdirSync(directory);

var modules_names=modules.map( file => path.parse(file).name )
var modules_paths=modules.map( file => directory + '/' + file )

console.log( modules_names );
console.log( modules_paths );

module.exports = {
  entry: ['./src/modules/DS18B20.js','./src/test.js'],
  externals: {
      'DS18B20': 'require("DS18B20");'
    },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'entry.bundle.js',
//    libraryTarget:'commonjs2',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        uglifyOptions: {
          //compress: true,
          ecma: 6,
          mangle: false // Disable name mangling to avoid this issue: https://github.com/espruino/Espruino/issues/1367
        },
        //sourceMap: true
      })
    ]
  },
};
wilberforce commented 6 years ago

So this is finding in the modules folder:

[ 'DS18B20', 'pid-controller', 'ws', 'www' ]
[ './src/modules/DS18B20.js',
  './src/modules/pid-controller.js',
  './src/modules/ws.js',
  './src/modules/www.js' ]