Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack UMD: Critical dependency... cannot be statically extracted

I'm trying to build a umd library with webpack; regardless of what I do get a warning:

WARNING in D:/Code/Node/sample.io/source/index.ts 3:24 Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

when I try to require('./index.js') the generated index.js I get:

Error: Cannot find module "."

For completeness here are all my files:

webpack.config.js:

module.exports = {
  entry: {
    index: __dirname + '/index'
  },
  output: {
    filename: 'index.js',
    library: 'mylib',
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  resolve: {
    root: __dirname,
    extensions: ['', '.ts', '.js'],
  },
  module: {
    loaders: [
      { test: /\.ts$/, loaders: ['awesome-typescript-loader'] }
    ]    
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "umd"
  },
  "exclude": [
    "node_modules"
  ]
}

package.json:

{
  "name": "foo",
  "version": "0.1.0",
  "devDependencies": {
    "awesome-typescript-loader": "^2.0.2",
    "typescript": "^2.0.0",
    "webpack": "^2.1.0-beta.17"
  }
}

index.ts:

export function MyFunc(params) {
  console.log("hello world");
}
  • node -v = v6.3.0
  • npm -v = 3.7.5

oddly, a friend of mine says this works without error for them. Although he is on node 4.2.6. If I change the module to commonjs it works perfectly fine without warnings or errors.

like image 253
Meirion Hughes Avatar asked Jul 15 '16 09:07

Meirion Hughes


2 Answers

I think you need "module": "commonjs" in tsconfig so typescript compilation will emit modules that are understandable to webpack, you will still get umd output from webpack

Hope this helps

like image 139
kruczy Avatar answered Nov 10 '22 03:11

kruczy


If you cannot change the module from umd to commonjs because you are just consuming it, and you do not have access to the source, you can use umd-compat-loader as a workaround. Add the following rule to your webpack.config.js:

module: {
    rules: [
        // other rules come here.
        {
            test: /node_modules[\\|/](name-of-the-umd-package)/,
            use: { loader: 'umd-compat-loader' }
        }
    ]
},

I have added a few more details to this thread.

like image 31
kittaakos Avatar answered Nov 10 '22 05:11

kittaakos