如何从Webpack捆绑包导出符号以在另一个JavaScript文件中使用?

时间:2018-09-23 03:46:33

标签: javascript webpack

我想在浏览器中使用一些JS模块。我为此创建了一个webpack项目。但是,我无法在目标JS文件中使用它们。

我想创建一个可以如下使用的包:

<html>
<head>
    <script src='ndarray-bundle.js'></script>
</head>
<body>
<script>
let ndx = ndarray(x, x_dims.slice(0)).transpose(0, 2, 3, 1);
</script>
</body>
</html>

为此,我使用以下webpack和package.json文件创建一个文件夹:

Webpack文件:

const path = require('path');
const webpack = require('webpack');
module.exports = {
  entry: './index.js',
  mode: 'development',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'ndarray-bundle.js'
  }
};

Package.json:

{
  "name": "packstuff-js",
  "version": "0.0.1",
  "description": "Just so I can pack ndarray stuff as one JS file",
  "main": "./lib/index.js",
  "scripts": {},
  "repository": {
    "type": "git",
    "url": "https://nothing/"
  },
  "keywords": [
    "ndarray"
  ],
  "author": "jeff",
  "license": "MIT",
  "dependencies": {
    "ndarray": "^1.0.18"
  },
  "devDependencies": {
    "webpack": "^4.19.1",
    "webpack-cli": "^3.1.0"
  }
}

我运行webpack并获得了一个捆绑文件,但是每次运行都会收到以下错误: ndarray is not defined

我已经使用了以下index.js内容,但无济于事:

版本1:

import ndarray from 'ndarray';

版本2:

require('ndarray');
export const ndarray = 'ndarray';

版本3:

const ndarray = require('ndarray');

版本4:

export ndarray from 'ndarray';

1 个答案:

答案 0 :(得分:0)

我遵循了这里的建议并定义了全局变量:

https://stackoverflow.com/a/37862805/5669031

我的index.js现在看起来像:

import ndarray from 'ndarray';

window.ndarray = ndarray;