Reputation: 2402
I have published a npm package.
It works fine when accessing via the global variable window.Router
in the browser, but when I try to import it using ES module in a Meteor application, it returns underfined
...
In the lib, I used named export and default export to be sure that the object Router
is accessible.
However none of the following returns the Router
object :
// default import
import Router from "jk-router";
// named import
import { Router } from "jk-router";
I am pretty sure there is something wrong with my Webpack config below, because I have published another npm package that I can import with no problem, the difference is that it's packaged with Gulp.
const path = require("path");
const Package = require("./package.json");
const isProd = process.argv.indexOf("-p") !== -1;
const filename = Package.name + (isProd ? ".min" : "");
module.exports = {
target: "web",
entry: {
bundle: path.join(__dirname, "src/router.js")
},
output: {
path: path.join(__dirname, "dist"),
filename: `${filename}.js`
},
resolve: {
extensions: [".js"],
modules: [path.join(__dirname, "src/js"), "node_modules"]
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: "babel-loader"
}
]
},
plugins: []
};
Upvotes: 2
Views: 3280
Reputation: 2402
After hours of digging, I finally found that I needed to define the output.libraryTarget
property with the umd
value in the webpack config. I have found nothing in the official documentation, only a reference on this page : https://webpack.js.org/configuration/
The final webpack config looks like this :
const path = require("path");
const Package = require("./package.json");
const isProd = process.argv.indexOf("-p") !== -1;
const filename = Package.name + (isProd ? ".min" : "");
module.exports = {
entry: {
bundle: path.join(__dirname, `src/jk-router.js`)
},
output: {
libraryTarget: "umd",
path: path.join(__dirname, "dist"),
filename: `${filename}.js`
},
resolve: {
extensions: [".js"],
modules: [path.join(__dirname, "src"), "node_modules"]
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
}
};
Upvotes: 6
Reputation: 35503
This is your problem, whenever you publish a NPM package, you need to specify the main file at package.json.
https://github.com/jalik/jk-router/blob/master/package.json#L5
I think that the main property points to wrong file, it should be "router.js" and not "jk-router.js".
If you want your filename to remain "jk-router.js" u can change the output field at webpack.config.js file to "jk-router.js"
Upvotes: 0