繁体   English   中英

如何使用可通过脚本元素使用的webpack创建独立模块?

[英]How to create standalone module with webpack usable through script element?

想想如果将库目标设置为“ umd”,则可以通过<script>标记使用输出,如果没有可用的模块系统,则将其附加到窗口。 但是,事实并非如此,或者某个地方犯了一个错误。.在这一点上需要另一双眼睛。

package.json是:

{
  "name": "scoped-css",
  "version": "2.1.9",
  "description": "Scoped CSS in two easy steps.",
  "main": "lib/index.js",
  "author": "Joshua Robinson",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/buildbreakdo/scoped-css.git"
  },
  "bugs": {
    "url": "https://github.com/buildbreakdo/scoped-css/issues"
  },
  "homepage": "https://github.com/buildbreakdo/scoped-css",
  "keywords": [
    "react",
    "reactive-root",
    "scope",
    "scoped",
    "inline",
    "style",
    "styles",
    "styling",
    "css",
    "CSS",
    "classes",
    "classname",
    "classnames",
    "util",
    "utility"
  ],
  "devDependencies": {
    "babel-cli": "^6.10.1",
    "babel-core": "^6.9.1",
    "babel-eslint": "^6.0.4",
    "babel-jest": "^12.1.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-polyfill": "^6.9.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-stage-0": "^6.5.0",
    "babel-preset-stage-1": "^6.5.0",
    "jest-cli": "^12.1.1",
    "js-beautify": "^1.6.3",
    "rimraf": "^2.5.2",
    "uglifyjs": "^2.4.10",
    "webpack": "^1.13.1"
  },
  "scripts": {
    "build": "webpack && babel src --out-dir lib && NODE_ENV='production' webpack && babel src --out-dir lib && npm run tests",
    "prebuild": "rimraf dist lib",
    "prepublish": "npm run build",
    "lint": "eslint .",
    "tests": "npm run lint && jest --coverage"
  },
  "dependencies": {}
}

webpack.config.js是:

// => webpage.config.js

var webpack = require('webpack');

var __DEV__ = JSON.parse(process.env.NODE_ENV !== 'production');

module.exports = {
  entry: './src/index.js',
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'stage-1']
        }
      }
    ]
  },
  output: {
    filename: __DEV__ ? 'dist/scoped-css.js' : 'dist/scoped-css.min.js',
    libraryTarget: 'umd',
    library: 'scoped-css'
  },
  plugins: __DEV__ ? [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    })
  ] : [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      }
    })
  ]
};

但是,当通过<script>标记包含模块并尝试使用代码时,看到以下内容:

standalone.html:21 Uncaught ReferenceError: Style is not defined

standalone.html如下:

<!-- standalone.html -->

<html>
    <head>
        <script src="../dist/scoped-css.js"></script>

    </head>
    <body>
        <ul>
            <li>foo</li>
            <li>bar</li>
        </ul>

        <ul>
            <li>baz</li>
            <li>klutz</li>
        </ul>

        <script>
            var ulElements = document.querySelectorAll('ul');

            var firstUlElement = ulElements[0];
            firstUlElement.className = Style.scoped();
            var firstUlStyle = document.createElement('style');
            firstUlStyle.type = 'text/css';
            firstUlStyle.innerHTML = Style.CSS( { 'li' : { color: 'red' } } );
            document.head.appendChild(firstUlStyle);

            var secondUlElement = ulElements[1];
            secondUlElement.className = Style.scoped();
            var secondUlStyle = document.createElement('style');
            secondUlStyle.type = 'text/css';
            secondUlStyle.innerHTML = Style.CSS( { 'li' : { backgroundColor: 'khaki' } } );
            document.head.appendChild(secondUlStyle);

            // See how both styles target all li? They do not impact each other
            // because each is scoped--this is called subtree scoping and is natively
            // supported in Firefox; native support has not landed in other browsers yet
            // so this serves as a poly-like-fill.
        </script>

    </body>
</html>

这是../dist/scoped-css.js的顶部和底部(已检查了网络面板,它正在正确加载,只是无法调用):

// => dist/scoped-css.js

(function webpackUniversalModuleDefinition(root, factory) {
    if(typeof exports === 'object' && typeof module === 'object')
        module.exports = factory();
    else if(typeof define === 'function' && define.amd)
        define([], factory);
    else if(typeof exports === 'object')
        exports["scoped-css"] = factory();
    else
        root["scoped-css"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

/******/    // The require function
/******/    function __webpack_require__(moduleId) {

/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;

/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };

/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/        // Flag the module as loaded
/******/        module.loaded = true;

/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }


/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;

/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;

/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";

/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

...
...
...

        if (true) {
            // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
            !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, __webpack_require__(2), __webpack_require__(1)], __WEBPACK_AMD_DEFINE_RESULT__ = function(requireamd) {
                var js_beautify = __webpack_require__(2);
                var css_beautify = __webpack_require__(1);

                return {
                    html_beautify: function(html_source, options) {
                        return style_html(html_source, options, js_beautify.js_beautify, css_beautify.css_beautify);
                    }
                };
            }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
        } else if (typeof exports !== "undefined") {
            // Add support for CommonJS. Just put this file somewhere on your require.paths
            // and you will be able to `var html_beautify = require("beautify").html_beautify`.
            var js_beautify = require('./beautify.js');
            var css_beautify = require('./beautify-css.js');

            exports.html_beautify = function(html_source, options) {
                return style_html(html_source, options, js_beautify.js_beautify, css_beautify.css_beautify);
            };
        } else if (typeof window !== "undefined") {
            // If we're running a web page and don't have either of the above, add our one global
            window.html_beautify = function(html_source, options) {
                return style_html(html_source, options, window.js_beautify, window.css_beautify);
            };
        } else if (typeof global !== "undefined") {
            // If we don't even have window, try global.
            global.html_beautify = function(html_source, options) {
                return style_html(html_source, options, global.js_beautify, global.css_beautify);
            };
        }

    }());

/***/ }
/******/ ])
});
;

怀疑是它与src/index.js (构建为dist/scoped-css.js之前的原始文件)中的导出处理方式dist/scoped-css.js

src/index.js底部(在构建之前)如下所示:

// Index.js
...
...
...
var Style = {
        scoped: scoped,
        CSS: CSS
    };

module.exports = Style;

同样,期望的是,如果../dist/scoped-css.js在脚本标签包含然后scoped-css.js可以称为像Style.CSS({})Style.scoped()附加到窗口) 。

另外,使用jest进行测试和模块加载,并且可以很好地调用它,因此知道代码没有损坏。 webpack配置有问题吗?

我这方面可能有些愚蠢,只需要另一双眼睛,盯着这个眼睛太久! 感谢您的宝贵时间和专业知识。

问题在于,由于该library: 'scoped-css'行,您的UMD使用scoped-css全局生成输出。 如果将其更改为library: 'Style' ,则代码将按预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM