cal*_*r47 11 javascript webpack
我有由 Webpack 管理的构建过程。它将我的所有文件捆绑在一起并生成一个bundle.js文件。很典型的图案。
但是,当我将该文件包含bundle.js在网页中时,导出的默认函数未定义。为什么我不能从网页上的全局范围访问导出的函数?
这是我的 webpack 配置:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/js/index.js',
output: {
path: path.resolve('dist'),
filename: 'bundle.js',
},
performance: {
hints: false,
},
resolve: {
modules: ['node_modules', path.join(__dirname, 'src'), 'assets'],
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: 'file-loader',
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: `bundle.css`,
}),
],
};
Run Code Online (Sandbox Code Playgroud)
这是一个简化的src/js/index.js:
import util from './util';
import as dependency from 'external-library';
import EventEmitter from 'events';
/**
* MyLibrary module
* @module MyLibrary
* @class
* @param {MyLibraryOptions} options - Options to initialize the module with
* @returns {Object} MyLibrary instance
*/
export default function MyLibrary(options) {
if (!(this instanceof MyLibrary)) {
return new MyLibrary(options);
}
//...Do a bunch of stuff.
}
Run Code Online (Sandbox Code Playgroud)
目标是bundle.js在网页上包含并访问脚本标签,例如:
var instance = new MyLibrary({option_1: value, ...})
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时MyLibrary总是未定义的。
更新:
在librarywebpack 配置中添加属性后,MyLibrary不是未定义的,但我不能调用它。现在是一个模块。
更新 2 --> 解决方案:
module.exports = {
entry: './src/js/index.js',
output: {
library: 'MyLibrary',
libraryTarget: 'umd',
libraryExport: 'default',
path: path.resolve('dist'),
filename: 'bundle.js',
}
...
Run Code Online (Sandbox Code Playgroud)
在 webpack 中,默认范围不是全局的。它包含匿名函数中的所有代码。要将您的库公开给浏览器的全局范围,请使用此答案。
你的 webpack 配置将如下所示:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/js/index.js',
output: {
library: 'MyLibrary',
path: path.resolve('dist'),
filename: 'bundle.js',
},
performance: {
hints: false,
},
resolve: {
modules: ['node_modules', path.join(__dirname, 'src'), 'assets'],
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: 'file-loader',
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: `bundle.css`,
}),
],
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3532 次 |
| 最近记录: |