1

我想将我的项目与 Webpack 集成。在我们使用 EJS 模板之前,我们只想将 CSS 和 JavaScript 等静态资产附加到body标签中。但是当我使用 EJS 加载器时,生成的 EJS 文件还有其他东西,如模块导出等。我该如何删除它?

以下是我的 Webpack 配置:

'use strict';

// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var htmlWebpackPlugin = require('html-webpack-plugin');
var extractTextPlugin = require('extract-text-webpack-plugin');
var copyWebpackPlugin = require('copy-webpack-plugin');
var bowerWebpackPlugin = require("bower-webpack-plugin")

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';

var frontend, path, version, output,settings,views;

version = '1.0';
path = require('path');
settings = require('./config/defaultSettings')
frontend = settings.fileStructure.frontend
output = settings.fileStructure.output
views = settings.fileStructure.views

module.exports = function makeWebpackConfig () {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   * Should be an empty object if it's generating a test build
   * Karma will set this when it's a test build
   */
  config.entry = isTest ? {} : {
    app: path.join(frontend,'/js/app.js'),
    vendor: ['jquery', 'angular'],
    controller: path.join(frontend,'/js/controller/controller.js'),
  };

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   * Should be an empty object if it's generating a test build
   * Karma will handle setting it up for you when it's a test build
   */
  config.output = isTest ? {} : {
    // Absolute output directory
    path: output,

    // Output path from the view of the page
    // Uses webpack-dev-server in development
    //publicPath: isProd ? '/' : 'http://localhost:8080/',//TODO which server

    // Filename for entry points
    // Only adds hash in build mode
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

    // Filename for non-entry points
    // Only adds hash in build mode
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isTest) {
    config.devtool = 'inline-source-map';
  } else if (isProd) {
    config.devtool = 'source-map';
  } else {
    config.devtool = 'eval-source-map';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */

    // Initialize module
  config.module = {
    preLoaders: [],
    loaders: [{
      // JS LOADER
      // Reference: https://github.com/babel/babel-loader
      // Transpile .js files using babel-loader
      // Compiles ES6 and ES7 into ES5 code
      test: /\.js$/,
      loader: 'babel',
      exclude: /node_modules/
    }, {
      // CSS LOADER
      // Reference: https://github.com/webpack/css-loader
      // Allow loading css through js
      //
      // Reference: https://github.com/postcss/postcss-loader
      // Postprocess your css with PostCSS plugins
      test: /\.css$/,
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files in production builds
      //
      // Reference: https://github.com/webpack/style-loader
      // Use style-loader in development.
      loader: isTest ? 'null' : extractTextPlugin.extract('style', 'css?sourceMap!postcss')
    }, {
      // ASSET LOADER
      // Reference: https://github.com/webpack/file-loader
      // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
      // Rename the file using the asset hash
      // Pass along the updated reference to your code
      // You can add here any file extension you want to get copied to your output
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file'
    }, {
      test: /\.ejs$/,
      loader: "ejs-loader"
    },
       {
      // HTML LOADER
      // Reference: https://github.com/webpack/raw-loader
      // Allow loading html through js
      test: /\.html$/,
      loader: 'raw'
    }]
  };

  // ISPARTA LOADER
  // Reference: https://github.com/deepsweet/isparta-loader
  // Instrument JS files with Isparta for subsequent code coverage reporting
  // Skips node_modules and files that end with .test.js
  if (isTest) {
    config.module.preLoaders.push({
      test: /\.js$/,
      exclude: [
        /node_modules/,
        /\.spec\.js$/
      ],
      loader: 'isparta-instrumenter'
    })
  }

  /**
   * PostCSS
   * Reference: https://github.com/postcss/autoprefixer
   * Add vendor prefixes to your css
   */
  config.postcss = [
    autoprefixer({
      browsers: ['last 2 version']
    })
  ];

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [];

  // Skip rendering index.html in test mode
  if (!isTest) {
    // Reference: https://github.com/ampedandwired/html-webpack-plugin
    // Render index.html
    config.plugins.push(
      new htmlWebpackPlugin({
        //template: 'frontend/1.0/views/login.ejs',
        template: 'ejs!'+path.join(views,'login.ejs'),
        filename: 'views/login.ejs',
        publicPath:'winston.peng',//TODO how to use?
        //chunks: ['app'],
        inject: 'body'
      }),

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files
      // Disabled when in test mode or not in build mode
      new extractTextPlugin('[name].[hash].css', {disable: !isProd})
    )

    /*config.plugins.push(
      new htmlWebpackPlugin({
        template: 'ejs!'+views+'/index.ejs',
        filename: 'views/index.ejs',
        inject: 'body'
      }),

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files
      // Disabled when in test mode or not in build mode
      new extractTextPlugin('[name].[hash].css', {disable: !isProd})
    )*/
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin(),

      // Copy assets from the public folder
      // Reference: https://github.com/kevlened/copy-webpack-plugin
      //new copyWebpackPlugin([{
      //  from: frontend
      //}]),

      //This will remove all modules in the vendor chunk from the app chunk. The bundle.js
      //will now contain just your app code, without any of its dependencies. These are in vendor.bundle.js.
      new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js"),

      new webpack.ProvidePlugin({
        _: "underscore"
      }),
      //Use Bower with Webpack.
      new bowerWebpackPlugin({
        modulesDirectories: [ path.join(frontend,'lib')],
        manifestFiles: ['bower.json', 'package.json'],
        includes: [/.*\.js/],
        excludes: [/.*\.less/],
        searchResolveModulesDirectories: true
      }
      )
    )
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  /*config.devServer = {
    contentBase: output,
    stats: 'minimal'
  };*/

  return config;
}();

下面是生成的login.ejs:

module.exports = function (obj) {
obj || (obj = {});
var __t, __p = '', __e = _.escape, __j = Array.prototype.join;
function print() { __p += __j.call(arguments, '') }
with (obj) {
__p += '<!doctype html>\n<html lang="en">\n<head>\n    ';
 include ('./_include/header') ;
__p += '\n    <style>\n        div.form-group{\n            margin-top:30px\n        }\n        .panel-success>.panel-heading{\n            background-color:#5CB85C;\n        }\n        .panel-title{\n            color:#FFFFFF;\n            font-weight:bold;\n        }\n\n        #username:focus{\n            border:solid 1px #8A9F00 !important;\n        }\n        form .help-block{\n            text-align:left !important;\n        }\n    </style>\n<link href="../app.c1dfd8952df85506c04a.css" rel="stylesheet"></head>\n<body>\n<div class="bf-docs-container bodyWrapper">\n    <div class="row" style="text-align:center;margin-top:100px !important;">\n        <div class="col-md-offset-3 col-md-6">\n            <div class="panel panel-success alignCenter ">\n                <div class="panel-heading">\n                    <h3 class="panel-title" style="text-align:center;">朗琴管理系统登录</h3>\n                </div>\n                <div class="panel-body">\n                    <form class="form form-horizontal" name="loginForm" action="/console/login" method="post">\n                        <div class="form-group">\n                            <label for="username" class="col-lg-2 control-label">用户名&lt;span class="required">*</span></label>\n                            <div class="col-lg-10">\n                                <input style="width:90%;" ng-model="username" class="form-control form-control-square" id="username" name="username" placeholder="请输入您的登陆账号">\n                            </div>\n                        </div>\n                        <div class="form-group">\n                            <label for="password" class="col-lg-2 control-label">密  码&lt;span class="required">*</span></label>\n                            <div class="col-lg-10">\n                                <input style="width:90%;" required class="form-control form-control-square" name="password" type="password" placeholder="请输入密码">\n                            </div>\n                        </div>\n                        <div class="form-group" style="color:#FF0000;text-align: left">\n                            <div class="col-lg-2"></div>\n                            <div class="col-lg-10">' +
__e(modelMap==null?"":modelMap.message) +
'</div>\n                        </div>\n                        <div class="form-group">\n                            <div class="col-lg-offset-2 col-lg-10">\n                                <button type="submit" class="form-control btn btn-success"  style="width:60%;float:left">登录</button>\n                                <!--<div style="line-height:34px;float:left">&nbsp;或&amp;nbsp;</div>\n                                <a href="/findpwd" style="line-height:34px;float:left">忘记密码?&lt;/a>-->\n                            </div>\n                        </div>\n                    </form>\n                </div>\n            </div>\n        </div>\n    </div>\n</div>\n<script type="text/javascript" src="../vendor.bundle.js"></script><script type="text/javascript" src="../controller.c1dfd8952df85506c04a.js"></script><script type="text/javascript" src="../app.c1dfd8952df85506c04a.js"></script></body>\n</html>';

}
return __p
}

我只想将静态资产附加到body标签中,而不做任何其他事情。

任何帮助表示赞赏。

4

0 回答 0